<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\TBaseDevice;
use app\models\TBaseSchool;
use app\models\TBaseDepartment;
use app\models\TCourseSigninInfo;
use app\models\TCourseSigninStudent;
use app\models\TCourseMember;
use app\models\TQuizInfo;
use app\models\TQuizResult;
use app\models\TQuizPaper;
use app\models\TQuizPaperRelation;
use app\models\TPaperTypeRelation;
use app\models\TBaseUserProfile;
use app\models\TCourseTask;
use app\models\TCourseTaskList;
use app\models\TCourseTaskReport;
use app\models\TCourseTaskFile;
use app\models\TCourseInfo;
use app\models\TQuizResultAnswer;
use app\common\Dictionary;
use app\common\ArrayHelper;
use app\common\PdUtils;
use Faker\Provider\Uuid;
/**
 * APP学员接口类
 * Created by PhpStorm.
 * User: gaoyj
 * Date: 2018/06/25
 */
class AppStudentController extends Controller
{
	public $enableCsrfValidation = false;
	public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /**
     * APP学员信息接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-06
     * @author: gaoyj
     */
    public function actionAppGetXmProfile()
    {
    	$error = array();
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => (object)[],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            $sql="SELECT
                    tbu.id,tbup.pet_name,tbup.url_image,tbup.mobilephone,tbup.type,tbup.gender,tbup.school_id,tbup.department_id,tbup.major_id,tbup.student_no,tbup.year,tbup.qianming,tbu.username,tbup.email,tbup.company,tbup.student_type,date_format(tbup.birthday,'%Y-%m-%d') as birthday,tbu.project_id,tbup.address,tbup.province,tbup.city
                FROM
                    t_base_user_profile tbup
                LEFT JOIN t_base_user tbu ON tbu.id = tbup.user_id
                WHERE
                    tbup.user_id = :userId AND tbup.del_flag=0 AND tbu.del_flag=0";
            $params = [':userId' => $userId];
            $userInfo = \Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryOne();
            if($userInfo)
            {
                if(!empty($userInfo['url_image']))
                {
                    $userInfo['url_image'] = Yii::$app->params['fileUrl'].$userInfo['url_image'];
                }
                if(!empty($userInfo['type']))
                {
                    $userInfo ['role_name'] = Dictionary::getPersonnel($userInfo);
                }
                else
                {
                    $userInfo ['role_name'] = '';
                }
                if(isset($userInfo['school_id']))
                {
                    $school_name = TBaseSchool::find()->select('school_name')->where('id=:id',[':id' => $userInfo['school_id']])->asArray()->one();
                    $userInfo['school_name'] = isset($school_name['school_name'])?$school_name['school_name']:'';
                }
                else
                {
                    $userInfo['school_name'] = '';
                }
                if(isset($userInfo['department_id']))
                {
                    $department_name = TBaseDepartment::find()->select('name')->where('id=:id',[':id' => $userInfo['department_id']])->asArray()->one();
                    $userInfo['department_name'] = isset($department_name['name'])?$department_name['name']:'';
                }
                else
                {
                    $userInfo['department_name'] = '';
                }
                if(isset($userInfo['major_id']))
                {
                    $major_name = \app\models\TBaseMajorDirectory::find()->select('name')->where('uuid=:id',[':id' => $userInfo['major_id']])->asArray()->one();
                    $userInfo['major_name'] = $major_name['name'];
                }
                else
                {
                    $userInfo['major_name'] = '';
                } 
                if(!empty($userInfo['project_id']))
                {
                    if ($userInfo['project_id']=='-1') {
                        $userInfo['project_name'] = '无联盟';
                    } else {
                        $project_name = \app\models\TBaseProject::find()->select('name')->where('id=:id',[':id' => $userInfo['project_id']])->asArray()->one();
                        $userInfo['project_name'] = $project_name['name'];
                    }
                }
                else
                {
                    $userInfo['project_name'] = '';
                }
                unset($userInfo['type']);
                $result = array(
                    "msg" => "登录成功",
                    "ver" => "1.5.0",
                    'data' => ArrayHelper::array_is_null($userInfo),
                    'code' => '200'
                );
            }
            elseif(empty($userInfo))
            {
                $result = array(
                    "msg" => "个人信息不全",
                    "ver" => "1.5.0",
                    'data' =>array(),
                    'code' =>'601'
                );
            }
            elseif($userInfo===false)
            {
                $result = array(
                    "msg" => "查询失败",
                    "ver" => "1.5.0",
                    'data' => array(),
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }
    /**
     * APP学员修改个人信息接口
     * @param int  userId:用户ID mobilephone:手机号 token:token projectId:联盟ID
     * @param int   school_id:学校ID major_id:专业ID student_no:学号
     * @param string  pet_name:姓名 gender:性别 email:邮箱 type:角色
     * @param string  province:省 city:市 address:详细地址 birthday:生日  //教师端传的字段（不是必传字段）
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-30
     * @author: gaoyj
     */
    public function actionAppUpdateXmProfile(){
        $error = array();
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error=array('用户id不能为空');
        $pet_name = !empty($_REQUEST['pet_name'])?$_REQUEST['pet_name']:$error=array('姓名不能为空');
        $gender = !empty($_REQUEST['gender'])?$_REQUEST['gender']:$error=array('性别不能为空');
        $mobilephone = !empty($_REQUEST['mobilephone'])?$_REQUEST['mobilephone']:$error=array('手机号不能为空');
        $email = isset($_REQUEST['email'])?$_REQUEST['email']:$error=array('邮箱不能为空');
        $type = isset($_REQUEST['type'])?$_REQUEST['type']:$error=array('角色不能为空');
        $school_id = isset($_REQUEST['school_id'])?$_REQUEST['school_id']:$error=array('学校不能为空');
        $major_id = isset($_REQUEST['major_id'])?$_REQUEST['major_id']:$error=array('专业不能为空');
        $project_id = !empty($_REQUEST['project_id'])?$_REQUEST['project_id']:'';
        $studentType = !empty($_REQUEST['studentType'])?$_REQUEST['studentType']:'';
        $student_no = isset($_REQUEST['student_no'])?$_REQUEST['student_no']:$error=array('学号不能为空');
        $token = !empty($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $userInfo = TBaseUserProfile::find()->select('email,student_no,school_id')->where('user_id=:userId and del_flag=0',[':userId'=>$userId])->asArray()->one();
            $uemail = $userInfo['email'];
            if ($email != $uemail) {
                $res = TBaseUserProfile::find()->where('email=:email and del_flag=0',[':email'=>$email])->one();
                if($res){
                    $result = [
                        'msg' => '邮箱已存在',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '603'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            if($type=="userType.student" || $type=="userType.teacher"){
                $ustudent_no = $userInfo['student_no'];
                $school = $userInfo['school_id'];
                if ($student_no!=$ustudent_no) {
                    $res = TBaseUserProfile::find()->select('student_no')->where('student_no=:student_no and school_id=:school_id and del_flag=0',[':student_no'=>$student_no,':school_id'=>$school_id])->one();
                    if($res){
                        $result = [
                            'msg' => '学号已存在',
                            'ver' => '1.5.0',
                            'data' => [],
                            'code' => '603'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
                if ($school_id!=$school) {
                    $res = TBaseUserProfile::find()->select('student_no')->where('student_no=:student_no and school_id=:school_id and del_flag=0',[':student_no'=>$student_no,':school_id'=>$school_id])->one();
                    if($res){
                        $result = [
                            'msg' => '学号已存在',
                            'ver' => '1.5.0',
                            'data' => [],
                            'code' => '603'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            }
            $transaction = Yii::$app->db->beginTransaction();
            $flag=1;
            try {
                $model = TBaseUserProfile::find()->where('user_id=:userId', [':userId' => $userId])->one();
                $img = $model->url_image;
                $model->attributes = $_REQUEST;
                $model->pet_name = $pet_name;
                $model->gender = $gender;
                $model->mobilephone = $mobilephone;
                $model->email = $email;
                $model->type = $type;
                $model->school_id = $school_id;
                $model->major_id = $major_id;
                $model->student_no = $student_no;
                if (!empty($studentType)) {
                    $model->student_type = $studentType;
                }
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s",time());
                if(!empty($_REQUEST['url_image'])){
                    $model->url_image = str_replace(Yii::$app->params['fileUrl'], "", $_REQUEST['url_image']);
                }else{
                    $model->url_image = $img;
                }
                if($model->validate() && $model->save())
                {
                    $model1 = \app\models\TBaseUser::findOne($userId);
                    if(!empty($project_id)){
                        $model1->project_id = $project_id;
                    }
                    $model1->email = $email;
                    $model1->update_by = $userId;
                    $model1->update_time = date("Y-m-d H:i:s",time());
                    if($model1->save()){
                        $flag=0;
                    }
                    // if(!empty($school_id)){
                    //     $sql="SELECT p.id FROM t_base_project p LEFT JOIN t_base_project_school s ON s.project_id=p.id WHERE s.school_id=:school_id AND p.del_flag=0 AND s.del_flag=0";
                    //     $params = [':school_id'=>$school_id];
                    //     $projectId = Yii::$app->db->createCommand($sql)->bindValues($params)->queryScalar();
                    //     $projectId = !empty($projectId)?$projectId:'-1';
                    //     $userModel = \app\models\TBaseUser::findOne($userId);
                    //     if (empty($userModel->project_id)) {
                    //         $userModel->project_id = $projectId;
                    //         $userModel->update_time = date('Y-m-d H:i:s',time());
                    //         $userModel->update_by = $userId;
                    //         if ($userModel->save()) {
                    //             $flag=0;
                    //         } else {
                    //             $flag=1;
                    //         }
                    //     } else {
                    //         $flag=0;
                    //     }
                        // $sql = "update t_base_user set project_id='".$projectId."',update_time='".date('Y-m-d H:i:s',time())."',update_by='".$userId."' where  del_flag=0 and id='".$userId."'";
                        // $res = Yii::$app->db->createCommand($sql)->execute();
                        // $Pmodel = \app\models\TBaseUserToProject::find()->where('user_id=:uid and del_flag=0',[':uid'=>$userId])->one();
                        // if(!empty($projectId)){
                        //     if(empty($Pmodel)){
                        //         $Pmodel = new \app\models\TBaseUserToProject();
                        //         $Pmodel->id = \Faker\Provider\Uuid::uuid();
                        //         $Pmodel->user_id = $userId;
                        //         $Pmodel->project_id=$projectId;
                        //         $Pmodel->del_flag=0;
                        //         $Pmodel->create_by=$userId;
                        //         $Pmodel->create_time = date('Y-m-d H:i:s', time());
                        //         if($Pmodel->validate() && $Pmodel->save()){
                        //             $flag=0;
                        //         }else{
                        //             $flag=1;
                        //         }
                        //     }
                        //     else
                        //     {
                        //         $Pmodel->project_id = $projectId;
                        //         $Pmodel->update_by = $userId;
                        //         $Pmodel->update_time = date('Y-m-d H:i:s', time());
                        //         if($Pmodel->validate() && $Pmodel->save()){
                        //             $flag=0;
                        //         }else{
                        //             $flag=1;
                        //         }
                        //     }
                        // }
                        // else
                        // {
                        //     if(!empty($Pmodel))
                        //     {
                        //         $Pmodel->del_flag = 1;
                        //         if($Pmodel->save()){
                        //             $flag=0;
                        //         }else{
                        //             $flag=1;
                        //         }
                        //     }
                        // }
                    // }
                    // else
                    // {
                    //     $flag=0;
                    // }
                }
                else
                {
                    $flag=1;
                }
            } catch (Exception $e) {
                $transaction->rollBack();
                $result = [
                    'msg' => '修改失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
            if($flag==0){
                Yii::$app->redis2->set('userId_' . $userId, $pet_name);
                $time = date("Y-m-d H:i:s");
                $userInfoData = [
                    'userid'=>$model1->old_id,
                    'birthday'=>'',
                    'city'=>empty($_REQUEST['city'])?'':$_REQUEST['city'],
                    'email'=> $email,
                    'gender'=> $gender=='gender.male'?'男':'女',
                    'institute'=> empty($school_id)?'' : PdUtils::getSchoolName($school_id),
                    'province'=>empty($_REQUEST['province'])?'':$_REQUEST['province'],
                    'specialty'=> empty($major_id)?'' :PdUtils::getMajorName($major_id),
                    'telephone'=>$mobilephone,
                    'username'=>$model1->username,
                    'realname'=>$pet_name,
                    'enrollmentnum'=>empty($student_no)?'':$student_no,
                    'modifiedtime'=> $time,
                    'bcourseid'=>'',
                    'projectid'=>$project_id,
                ];
                @PdUtils::SaveMongoData($userInfoData, 'user');
                $transaction->commit();
                $result = [
                    'msg' => '修改成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => true,
                    'code' => '200'
                ];
            }else{
                $transaction->rollBack();
                $result = [
                    'msg' => '修改失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /*
     * 头像上传
     */
    public function actionAppHeadImagesInput(){
        if(!empty($_FILES)){
            $path = 'files'.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.date("Ym").DIRECTORY_SEPARATOR;
            if(!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)){
                mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
            }
            $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
            $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
            if(move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)){
                $result = array(
                    "msg"=> "保存成功",
                    "ver"=> "1.5.0",
                    'data'=>\Yii::$app->params['fileUrl'].$uri, 
                    'success' => true,
                    'code'=>'200'
                );
            }else{
                $result = array(
                    "msg"=> "保存失败",
                    "ver"=> "1.5.0",
                    'data'=>array(),
                    'success' => false,
                    'code'=>'400'
                );
            }
        }else{
            $result = array(
                "msg"=> "缺少参数",
                "ver"=> "1.5.0",
                'data'=>array(),
                'success' => false,
                'code'=>'601'
            );
        }
        Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
    }
    /**
     * APP学校列表接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-30
     * @author: gaoyj
     */
    public function actionAppGetSchoolPageList()
    {
        $error = array();
        $school_name = !empty($_REQUEST['school_name'])?$_REQUEST['school_name']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $school_list = TBaseSchool::find()->select('id,school_name,pinyin,school_code')->where(['del_flag' => 0])->asArray()->all();
            if($school_list)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($school_list),
                    'success' => true,
                    'code' => 200,
                ];
            }
            elseif(empty($school_list))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 404,
                ];
            }
            elseif($school_list===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP学院列表接口
     * @param int  school_id:学校ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-30
     * @author: gaoyj
     */
    public function actionAppGetDepartmentPageList()
    {
        $error = array();
        $school_id = !empty($_REQUEST['school_id'])?$_REQUEST['school_id']:$error[]=array('学校ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        $where = '';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $department = TBaseDepartment::find()->select('id,name')->where('school_id=:school_id and del_flag=0', [':school_id' => $school_id])->asArray()->all();
            if($department)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($department),
                    'success' => true,
                    'code' => 200,
                ];
            }
            elseif(empty($department))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 404,
                ];
            }
            elseif($department===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP专业列表接口
     * @param int  school_id:学校ID department_id:院系ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-30
     * @author: gaoyj
     */
    public function actionAppGetMajorPageList()
    {
        $error = array();
        $school_id = !empty($_REQUEST['school_id'])?$_REQUEST['school_id']:'';
        $department_id = !empty($_REQUEST['department_id'])?$_REQUEST['department_id']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        $where = '';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(!empty($school_id))
            {
                $where .= " and school_id='".$school_id."'";
            }
            if(!empty($department_id))
            {
                $where .= " and department_id='".$department_id."'";
            }
            $major_sql = "SELECT id,name FROM t_base_major WHERE del_flag=0 ".$where." ORDER BY id";
            $major = Yii::$app->db->createCommand($major_sql)->queryAll();
            if($major)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($major),
                    'success' => true,
                    'code' => 200,
                ];
            }
            elseif(empty($major))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 404,
                ];
            }
            elseif($major===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP专业目录列表接口(新)
     * @param int  school_id:学校ID department_id:院系ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-04-22
     * @author: gaoyj
     */
    public function actionAppGetMajorPageListNew(){
        $error = array();
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        $where = '';
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device)){
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $major = \app\models\TBaseMajorDirectory::find()->select('uuid as id,name,pinyin')->where(['del_flag'=>0])->asArray()->all();
            if($major){
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($major),
                    'success' => true,
                    'code' => 200,
                ];
            }elseif(empty($major)){
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 404,
                ];
            }elseif($major===false){
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => 400,
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP发起签到事件接口
     * @param int  party_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-09
     * @author: gaoyj
     */
    public function actionAppSigninInfoAdd()
    {
        $error = array();
        $party_id = isset($_REQUEST['party_id'])?$_REQUEST['party_id']:$error=array('班级id不能为空');
        $course_id = isset($_REQUEST['course_id'])?$_REQUEST['course_id']:$error=array('课程id不能为空');
        $user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:$error=array('用户id不能为空');
        $start_time = isset($_REQUEST['start_time'])?$_REQUEST['start_time']:$error=array('开始时间不能为空');
        $end_time = isset($_REQUEST['end_time'])?$_REQUEST['end_time']:$error=array('结束时间不能为空');
        $code = isset($_REQUEST['code'])?$_REQUEST['code']:$error=array('签到码不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model = new TCourseSigninInfo();
                $model->attributes = $_REQUEST;
                $model->id = Uuid::uuid();
                $model->party_id = $party_id;
                $model->course_id = $course_id;
                $model->user_id = $user_id;
                $model->start_time = $start_time;
                $model->end_time = $end_time;
                $model->code = $code;
                $model->type = 'signinType.common';
                $model->is_location = '0';
                $model->create_by = $user_id;
                $model->create_time = date("Y-m-d H:i:s",time());
                $model->del_flag = 0;
                $model->status = 'usingStatus.start';
                if($model->validate() && $model->save())
                {
                    $flag = true;
                    $student = TCourseMember::find()->where('class_id=:class_id and course_id=:course_id and del_flag=0', [':class_id' => $party_id, ':course_id' => $course_id])->asArray()->all();
                    foreach ($student as $key => $val)
                    {
                        $info = TCourseSigninStudent::find()->where('sign_id=:sid and user_id=:uid',[':sid'=>$model->id,':uid'=>$val['user_id']])->one();
                        if(empty($info))
                        {
                            $signStudent = new TCourseSigninStudent();
                            $signStudent->id = Uuid::uuid();
                            $signStudent->sign_id = $model->id;
                            $signStudent->user_id = $val['user_id'];
                            $signStudent->status = 'yesOrNo.no';
                            $signStudent->student_status = "signinStatus.default";
                            $signStudent->del_flag = 0;
                            $signStudent->create_by = $user_id;
                            $signStudent->create_time = date('Y-m-d H:i:s',time());
                            $res = $signStudent->save(false);
                            if($res != false){
                                $flag = TRUE;
                            }else{
                                $flag = false;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if($flag)
                    {
                        $transaction->commit();
                        $result = [
                            "msg"=> "添加成功",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'code'=>'200'
                        ];
                    }
                    else
                    {
                        $transaction->rollback();
                        $result = [
                            "msg"=> "添加失败",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'code'=>'400'
                        ];
                    }
                }
                else
                {
                    $result = [
                        "msg"=> "添加失败",
                        "ver"=> "1.5.0",
                        'data'=>array(),
                        'code'=>'400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $result = [
                    "msg" => "操作失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /**
     * APP获取签到事件接口
     * @param int  party_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-21
     * @author: gaoyj
     */
    public function actionAppGetSigninInfo()
    {
        $error = array();
        // $party_id = isset($_REQUEST['party_id'])?$_REQUEST['party_id']:$error=array('班级id不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error=array('用户id不能为空');
        $signId = !empty($_REQUEST['signId']) && isset($_REQUEST['signId']) ? $_REQUEST['signId'] : '';
        $courseId = !empty($_REQUEST['course_id'])?$_REQUEST['course_id']:$error=array('课程id不能为空');
        $projectId = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = !empty($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => ['id' => '','code' => '','start_time'=>'','end_time' => ''],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $where = '';
            if (strlen($signId)>0) {
                $where = " AND tcsi.id='".$signId."'";
            }
            // $sign = TCourseSigninInfo::find()->select('id,code')->where('party_id=:party_id and course_id=:courseId and status=:status and del_flag=0 and start_time<:time and end_time>:time',[':party_id' => $party_id,':courseId' => $courseId,':status' => 'usingStatus.start',':time' => date("Y-m-d H:i:s")])->asArray()->orderBy('id desc')->one();
            //修改：未签到的签到事件也能获取到（去掉了AND tcss.student_status='signinStatus.default'）
            $sql = "SELECT tcsi.id,tcsi.code,tcsi.start_time,tcsi.end_time,tcsi.old_id FROM t_course_signin_info tcsi LEFT JOIN t_course_signin_student tcss ON tcsi.id=tcss.sign_id WHERE tcsi.course_id=:courseId AND tcss.user_id=:userId AND tcsi.status=:status AND '".time()."' BETWEEN UNIX_TIMESTAMP(tcsi.start_time) AND UNIX_TIMESTAMP(tcsi.end_time) AND tcsi.type='signinType.common' AND tcsi.del_flag=0 AND tcss.del_flag=0 $where ORDER BY tcsi.create_time DESC";
            $params = [':courseId' => $courseId,':userId' => $userId,':status' => 'usingStatus.start'];
            $sign = Yii::$app->db->createCommand($sql)
                            ->bindValues($params)
                            ->queryOne();
            if($sign)
            {
                $sign = ArrayHelper::array_is_null($sign);
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $sign,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($sign))
            {
                $result = [
                    'msg' => '没有签到',
                    'ver' => '1.5.0',
                    'data' => ['id' => '','code' => '','start_time'=>'','end_time' => ''],
                    'success' => false,
                    'code' => '404'
                ];
            }
            elseif($sign===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['id' => '','code' => '','start_time'=>'','end_time' => ''],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP学生签到接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-09
     * @author: gaoyj
     */
    public function actionAppDoSigninInfo()
    {
        $error = array();
        $sign_id = isset($_REQUEST['sign_id'])?$_REQUEST['sign_id']:$error[]=array('签到事件ID不能为空');
        $code = isset($_REQUEST['code'])?$_REQUEST['code']:$error[]=array('签到码不能为空');
        $user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $sign = TCourseSigninInfo::find()->where('id=:sign_id and del_flag=0',[':sign_id'=>$sign_id])->one();
            if($sign)
            {
                $time = date("Y-m-d H:i:s",time());
                if($time > $sign->end_time)
                {
                    $result = [
                        'msg' => '签到已结束',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                if($time < $sign->start_time)
                {
                    $result = [
                        'msg' => '签到未开始',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model = TCourseSigninStudent::find()->where('sign_id=:sid and user_id=:uid and del_flag=0',[':sid'=>$sign_id,':uid'=>$user_id])->one();
                if (empty($model)) {
                    $result = [
                        'msg' => '没有该签到事件',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '404'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model->status = "yesOrNo.yes";
                $model->code = $code;
                $model->signin_time = date('Y-m-d H:i:s');
                $model->student_status = 'signinStatus.sign';
                $model->sign_person_type = 2;
                $model->update_by = $user_id;
                $model->update_time = date('Y-m-d H:i:s');
                $res = $model->update();
                if($res)
                {
                    $result = [
                        'msg' => '签到成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '签到失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $result = [
                    'msg' => '没有该签到事件',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP获取学员签到记录接口
     * @param int  party_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-22
     * @author: gaoyj
     * 姜宏煜 改： 去掉 sql：AND UNIX_TIMESTAMP(tcs.end_time)<'".time()."'  
     */
    public function actionAppGetSigninList()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $year = isset($_REQUEST['year'])?$_REQUEST['year']:$error[]=array('年份不能为空');
        $month = isset($_REQUEST['month'])?$_REQUEST['month']:$error[]=array('月份不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ]; 
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            if((date('m')==$month && date('Y')==$year) || (date('m')<$month && date('Y')==$year)){
                $sql = "SELECT
                            tcss.id,IFNULL(tcs.start_time,'') as start_time,tcs.end_time,tcss.signin_time,tcss.student_status
                        FROM
                            t_course_signin_info tcs
                        LEFT JOIN t_course_signin_student tcss ON tcss.sign_id = tcs.id
                        WHERE
                            tcs.course_id = '".$courseId."'
                        AND tcss.user_id = '".$userId."'
                        AND UNIX_TIMESTAMP(tcs.start_time) BETWEEN '".mktime(0,0,0,$month,1,$year)."'
                        AND '".time()."'
                        AND tcs.del_flag=0
                        AND tcss.del_flag=0";
            }else{
                $sql = "SELECT
                            tcss.id,IFNULL(tcs.start_time,'') as start_time,tcs.end_time,tcss.signin_time,tcss.student_status
                        FROM
                            t_course_signin_info tcs
                        LEFT JOIN t_course_signin_student tcss ON tcss.sign_id = tcs.id
                        WHERE
                            tcs.course_id = '".$courseId."'
                        AND tcss.user_id = '".$userId."'
                        AND UNIX_TIMESTAMP(tcs.start_time) BETWEEN '".mktime(0,0,0,$month,1,$year)."'
                        AND '".mktime(23,59,59,$month,date('t'),$year)."'
                        AND tcs.del_flag=0
                        AND tcss.del_flag=0";
            }
            $list = Yii::$app->db->createCommand($sql)->queryAll();
            if($list)
            {
                foreach ($list as $key =>& $val)
                {
                    if($val['signin_time']=='0000-00-00 00:00:00')
                    {
                        $val['signin_time'] = $val['end_time'];
                    }
                    $weekarray=array("日","一","二","三","四","五","六");
                    $val['week'] = "星期".$weekarray[date('w',strtotime($val['signin_time']))];
                    unset($val['end_time']);
                }
                $list = ArrayHelper::array_sort($list,'signin_time');
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $list,
                    'success' => true,
                    'code' => '200'
                ]; 
            }
            elseif(empty($list))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ]; 
            }
            elseif($list===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ]; 
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP查看测验信息接口
     * @param int  userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-11
     * @author: gaoyj
     */
    public function actionAppGetQuizInfo()
    {
        $error = array();
        $quizId = isset($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:'';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
//            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
//            if(empty($device))
//            {
//                $result = [
//                    'msg' => 'Token失效',
//                    'ver' => '1.5.0',
//                    'data' => [],
//                    'code' => '900'
//                ];
//                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
//            }
            $quizInfo = TQuizInfo::find()->select('timekeeping,empirical_num,renewal_num,total_score,end_time,quiz_name,result_setting,quiz_type,quiz_status,del_flag,begin_time,result_end_time')->where('id=:id', [':id' => $quizId])->asArray()->one();
            if($quizInfo)
            {
                $quizInfo = ArrayHelper::array_is_null($quizInfo);
                $quizInfo['total_score'] = !empty($quizInfo['total_score'])?$quizInfo['total_score']:0;
                $quizInfo['result_num'] = TQuizResult::find()->where('quiz_id=:quizId AND status!=:status AND create_by=:userId AND del_flag=0', [':quizId' => $quizId, ':userId' => $userId, ':status' => 'quizResultStatus.answerIn'])->count();
                $paper_id = TQuizPaperRelation::find()->where('quiz_id=:quizId AND del_flag=0', [':quizId' => $quizId])->one();
                if($paper_id)
                {
                    $type = TPaperTypeRelation::find()->select('type,question_num')->where('paper_id=:paperId AND del_flag=0', [':paperId' => $paper_id->paper_id])->asArray()->all();
                    $quizInfo['test'] = Dictionary::getQuestionType(ArrayHelper::array_is_null($type));
                    $total_num = 0;
                    foreach ($type as $key => $value)
                    {
                        $total_num+=$value['question_num'];
                    }
                    $quizInfo['total_num'] = $total_num;
                    $quizInfo['paperType'] = 'paperType.objective';
                    // $arr_Array = array_reduce($data,function(&$arr_Array,$v){
                    //     $arr_Array[$v['type']] = $v['question_num'];
                    //     return $arr_Array;
                    // });
                    // $paperType = TQuizPaper::find()->select('paper_type')->where('id=:id and del_flag=0', [':id' => $paper_id->paper_id])->one();
                    $paperType = TPaperTypeRelation::find()->select('type')->where('paper_id=:id and del_flag=0',[':id'=>$paper_id->paper_id])->asArray()->all();
                    if($paperType)
                    {
                        foreach ($paperType as $key => $value)
                        {
                            if($value['type']=='questionType.shortAnswer' || $value['type']=='questionType.discuss' || $value['type']=='questionType.fillIn' || $value['type']=='questionType.calculation')
                            {
                                $quizInfo['paperType'] = 'paperType.subjective';
                                break;
                            }
                        }
                        // $quizInfo['paperType'] = $paperType->paper_type;
                        $quizInfo['paper_id'] = $paper_id->paper_id;
                    }
                    else
                    {
                        $quizInfo['paperType'] = '';
                        $quizInfo['paper_id'] = '';
                    } 
                }
                else
                {
                    $quizInfo['test'] = [];
                    $quizInfo['paperType'] = '';
                    $quizInfo['paper_id'] = '';
                    $quizInfo['total_num'] = 0;
                }
                $quizInfo['result_status'] = '';
                $quizInfo['student_status'] = 'submitStatus.myself';//状态：学生是自己提交的还是系统自动提交的
                // $rsql = "SELECT id,begin_time FROM t_quiz_result WHERE quiz_id='".$quizId."' AND create_by='".$userId."' AND status IN('quizResultStatus.answerIn','') AND del_flag=0";
                $rsql = "SELECT id,begin_time,status,back_result_end_time FROM t_quiz_result WHERE quiz_id='".$quizId."' AND create_by='".$userId."' AND del_flag=0";
                $res = Yii::$app->db->createCommand($rsql)->queryOne();
                if ($res['status']=='quizResultStatus.answerIn' || $res['status']=='') {
                    if (!empty($res['begin_time'])) {
                        $time = time()-strtotime($res['begin_time']);
                    } else {
                        $time = 0;
                    }
                    //考试时长为空时
                    if (empty($quizInfo['timekeeping'])) {
                        $quizInfo['timekeeping'] = 0;
                        //学生最晚答卷时间已到，自动提交
                        if (!empty($quizInfo['result_end_time'])) {
                            if (strtotime($quizInfo['result_end_time'])<time()) {
                                $ress = $this->AppSubmitAnswer($res['id'],$quizId,$quizInfo['paperType'],$quizInfo['total_num'],$userId);
                                $quizInfo['student_status'] = 'submitStatus.system';
                            }
                        }
                    }
                    //考试时长不为空时
                    if (!empty($quizInfo['timekeeping'])) {
                        //学生最晚答卷时间为空时，考试时长到了自动提交
                        if (empty($quizInfo['result_end_time'])) {
                            if ($quizInfo['timekeeping']-floor($time/60)<=0) {
                                $ress = $this->AppSubmitAnswer($res['id'],$quizId,$quizInfo['paperType'],$quizInfo['total_num'],$userId);
                                $quizInfo['student_status'] = 'submitStatus.system';
                            }
                        } else {
                            //学生最晚答卷时间不为空时，考试时长或学生最晚答卷时间到了自动提交
                            if ($quizInfo['timekeeping']-floor($time/60)<=0 || strtotime($quizInfo['result_end_time'])<time()) {
                                $ress = $this->AppSubmitAnswer($res['id'],$quizId,$quizInfo['paperType'],$quizInfo['total_num'],$userId);
                                $quizInfo['student_status'] = 'submitStatus.system';
                            }
                        }
                    }
                } else if ($res['status']=='quizResultStatus.backed') {
                    $quizInfo['result_status'] = 'quizResultStatus.backed';
                    //退回状态，最晚交卷时间不为空时，时间到了自动交卷
                    if (!empty($res['back_result_end_time']) && $res['back_result_end_time']!='0000-00-00 00:00:00') {
                        $quizInfo['result_end_time'] = $res['back_result_end_time'];
                        if (strtotime($res['back_result_end_time'])<time()) {
                            $ress = $this->AppSubmitAnswer($res['id'],$quizId,$quizInfo['paperType'],$quizInfo['total_num'],$userId);
                            $quizInfo['student_status'] = 'submitStatus.system';
                        }
                    }
                }
                $record = TQuizResult::find()->select('id,begin_time,end_time,score')
                        ->where('quiz_id=:quizId AND create_by=:userId AND status=:status AND del_flag=0', [':quizId' => $quizId, ':userId' => $userId, ':status' => 'quizResultStatus.marked'])
                        ->orderBy('end_time desc')
                        ->limit(1)
                        ->asArray()
                        ->one();
                if($record)
                {
                    $record = ArrayHelper::array_is_null($record);
                    if (empty($record['end_time']) || $record['end_time']=='0000-00-00 00:00:00') {
                        $end_time = $quizInfo['end_time'];
                    } else {
                        $end_time = $record['end_time'];
                    }
                    // $record['answer_time'] = $this->secToTime(strtotime($record['end_time'])-strtotime($record['begin_time']));
                    if (!empty($record['begin_time'] && $record['begin_time']!='0000-00-00 00:00:00')) {
                        $record['answer_time'] = ceil((strtotime($end_time)-strtotime($record['begin_time']))/60);
                    } else {
                        $record['answer_time'] = 0;
                    }
                    if($quizInfo['timekeeping']>0 && $record['answer_time']>$quizInfo['timekeeping']){
                        $record['answer_time'] = $quizInfo['timekeeping'];
                    }
                    // $record['end_time'] = date("Y-m-d",strtotime($record['end_time']));
                    $record['score'] = !empty($record['score'])?$record['score']>$quizInfo['total_score']?$quizInfo['total_score']:$record['score']:'0.00';
                    unset($record['begin_time']);
                    $quizInfo['result_id'] = '';
                }
                else
                {
                    $record = [];
                    $res_sql = "SELECT id FROM t_quiz_result WHERE quiz_id='".$quizId."' AND create_by='".$userId."' AND status IN('quizResultStatus.answerIn','','quizResultStatus.backed') AND del_flag=0";
                    $result_id = Yii::$app->db->createCommand($res_sql)->queryOne();
                    if(!empty($result_id))
                    {
                        $quizInfo['result_id'] = $result_id['id'];
                    }
                    else
                    {
                        $quizInfo['result_id'] = '';
                    }
                }
                // $res_sql = "SELECT id FROM t_quiz_result WHERE quiz_id=".$quizId." AND create_by=".$userId." AND status IN('quizResultStatus.answerIn','') AND del_flag=0";
                // $result_id = Yii::$app->db->createCommand($res_sql)->queryOne();
                // $result_id = TQuizResult::find()->select('id')->where('quiz_id=:quizId AND create_by=:userId AND status=:status AND is_evaluated=:is_evaluated AND del_flag=0', [':quizId' => $quizId, ':userId' => $userId, ':status' => '', ':is_evaluated' => 'yesOrNo.no'])->one();
                // if(!empty($result_id))
                // {
                //     $quizInfo['result_id'] = intval($result_id['id']);
                // }
                // else
                // {
                //     $quizInfo['result_id'] = 0;
                // }

                $result = [
                    'msg' => '查看成功',
                    'ver' => '1.5.0',
                    'data' => array_merge($quizInfo,array('answer' => (object)$record)),
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($quizInfo))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            elseif($quizInfo===false)
            {
                $result = [
                    'msg' => '查看失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            Yii::$app->end(json_encode($result));
        }
    }
    public function AppSubmitAnswer($resultId='',$quizId='',$paperType='',$ques_num='',$userId='')
    {
        $error = array();
        $resultId = !empty($resultId)?$resultId:$error[]=array('答题卡ID不能为空');
        $quizId = !empty($quizId)?$quizId:$error[]=array('测验ID不能为空');
        $paperType = !empty($paperType)?$paperType:$error[]=array('试卷类型不能为空');
        $ques_num = !empty($ques_num)?$ques_num:$error[]=array('总题数不能为空');
        $userId = !empty($userId)?$userId:$error[]=array('用户ID不能为空');
        if(!empty($error))
        {
            return false;
        }
        else
        {
            $time = date('Y-m-d H:i:s');
            $answerQuestion_sql = "select ques_id from t_quiz_result_answer where result_id='".$resultId."' and del_flag=0";
            $answerQuestion = \Yii::$app->db->createCommand($answerQuestion_sql)->queryColumn();
            //查询本卷的试题id
            $paper = \app\models\TQuizPaperRelation::find()->where('quiz_id=:qid and del_flag=:d',[':qid'=>$quizId,':d'=>0])->one();
            $paperQuestion_sql = "select a.ques_id from t_quiz_paper_ques_relation a left join t_quiz_question b on a.ques_id=b.id where a.paper_id='".$paper->paper_id."' and a.del_flag=0 and b.del_flag=0";
            $paperQuestion = \Yii::$app->db->createCommand($paperQuestion_sql)->queryColumn();
            //查询学员未答题的试题id
            $incompleteQuestion = array_diff($paperQuestion, $answerQuestion);
            if(!empty($incompleteQuestion)){
                $transaction = \Yii::$app->db->beginTransaction();
                //插入学员答题卡的答案表
                foreach($incompleteQuestion as $v){
                    $resultAnswer = new TQuizResultAnswer();
                    $resultAnswer->id = \Faker\Provider\Uuid::uuid();
                    $resultAnswer->result_id = $resultId;
                    $resultAnswer->ques_id = $v;
                    $resultAnswer->is_correct = 'yesOrNo.no';
                    $resultAnswer->answer = '';
                    $resultAnswer->answer_right = '';
                    $resultAnswer->points_awarded = '';
                    $resultAnswer->answer_time = $time;
                    $resultAnswer->create_by = $userId;
                    $resultAnswer->create_time = $time;
                    $resultAnswer->del_flag = 0;
                    $resultAnswerRes = $resultAnswer ->save();
                    if($resultAnswerRes !=false){
                        $resultAnswerFlag = true;
                    }else{
                        $resultAnswerFlag = false;
                        break;
                    }     
                } 
                if($resultAnswerFlag){
                    $transaction->commit();
                }else{
                    $transaction->rollback();
                    return false;
                }
            }
            $model = TQuizResult::findOne($resultId);
            if($paperType=='paperType.subjective')
            {
                // $sql = "SELECT COUNT(*) as answer_ques_num FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                // $params = [':resultId' => $resultId];
                // $answer_ques_num = \Yii::$app->db->createCommand($sql)
                //             ->bindValues($params)
                //             ->queryScalar();
                
                $model->quiz_id = $quizId;
                $model->end_time = date("Y-m-d H:i:s");
                $model->status = 'quizResultStatus.submitted';
                $model->answer_ques_num = !empty($answerQuestion)?count($answerQuestion):0;
                $model->total_ques_num = !empty($paperQuestion)?count($paperQuestion):0;
                $model->score = '';
                $model->is_invalid = 'yesOrNo.yes';
                $model->is_evaluated = '';
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s");
                if($model->validate() && $model->save())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                $sql = "SELECT SUM(points_awarded) as score FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                $params = [':resultId' => $resultId];
                $answer = \Yii::$app->db->createCommand($sql)
                            ->bindValues($params)
                            ->queryOne();
                
                $model->quiz_id = $quizId;
                $model->end_time = date("Y-m-d H:i:s");
                $model->status = 'quizResultStatus.marked';
                $model->score = $answer['score'];
                $model->answer_ques_num = !empty($answerQuestion)?count($answerQuestion):0;
                $model->total_ques_num = !empty($paperQuestion)?count($paperQuestion):0;
                $model->is_invalid = 'yesOrNo.yes';
                $model->is_evaluated = 'quizResultStatus.marked';
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s");
                if($model->validate() && $model->save())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
    /**
     * APP查看测验时间接口
     * @param int resultId:答题卡ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-31
     * @author: gaoyj
     */
    public function actionAppGetQuizTime()
    {
        $error = array();
        $resultId = isset($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:'';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
//            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
//            if(empty($device))
//            {
//                $result = [
//                    'msg' => 'Token失效',
//                    'ver' => '1.5.0',
//                    'data' => [],
//                    'code' => '900'
//                ];
//                Yii::$app->end(json_encode($result));
//            }
            $result = TQuizResult::findOne($resultId);
            if($result)
            {
                $timekeeping = TQuizInfo::find()->select('timekeeping')->where('id=:id', [':id' => $result->quiz_id])->asArray()->one();
                if(!empty($result->begin_time))
                {
                    $time = time()-strtotime($result->begin_time);
                }
                else
                {
                    $time = 0;
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'time' => ($timekeeping['timekeeping']*60-$time)>=0?$timekeeping['timekeeping']*60-$time:0,
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP任务信息接口
     * @param int  taskId:任务ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-31
     * @author: gaoyj
     */
    public function actionAppGetCourseTask()
    {
        $error = array();
        $taskId = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('任务ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $task = TCourseTask::find()
                    ->select('id,task_title,task_content,task_score,group_way,end_time,task_status,task_experience,start_time,deadline')
                    ->where('id=:id', [':id' => $taskId])
                    ->asArray()
                    ->one();
            if($task)
            {
                $task = ArrayHelper::array_is_null($task);
                if ($task['start_time']==="0000-00-00 00:00:00") {
                    $task['start_time'] = '';
                }
                if ($task['deadline']==="0000-00-00 00:00:00") {
                    $task['deadline'] = '';
                }
                $task['current_time'] = date("Y-m-d H:i:s");
                $task_files = \app\models\TCourseTaskUploadFile::find()->select('id,name,type,file_uri,mime')->where('task_id=:taskId and del_flag=0',[':taskId'=>$taskId])->asArray()->all();
                if($task_files){
                    foreach ($task_files as $value) {
                        $file_info=array();
                        if ($value['mime'] == 'image/jpeg' || $value['mime'] == 'image/jpg' ||$value['mime'] == 'image/png'||$value['mime'] == 'image/*' )
                        {
                            $file_info=array(
                                'filename'=>$value['name'],
                                'uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'type'=>'resourceType.image',
                                'fid'=>$value['id']
                            );
                            $task['task_files'][] = $file_info;
                        } 
                        elseif ($value['mime'] == 'video/mp4')
                        { 
                            $task['task_files'][] = array(
                                'filename'=>$value['name'],
                                'uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'type'=>'resourceType.video',
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3')
                        { 
                            $task['task_files'][] = array(
                                'filename'=>$value['name'],
                                'uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'type'=>'resourceType.audio',
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation'|| $value['mime'] == 'application/vnd.ms-powerpoint'|| $value['mime'] == 'text/plain'|| $value['mime'] == 'application/pdf'|| $value['mime'] == 'application/octet-stream')
                        {
                            $html_url = BaseController::getFileHtmlUrl( Yii::$app->params['fileUrl'].$value['file_uri']);
                            $task['task_files'][] = array(
                                'filename'=>$value['name'],
                                'uri'=>$html_url,
                                'type'=>'resourceType.document',
                                'fid'=>$value['id']
                            );
                        }
                    }
                } else {
                    $task['task_files'] = [];
                }
                $task['report_status'] = '';
                $sql = "SELECT
                            tctl.id,tctl.task_title,tctl.task_content,tctl.task_status,'yesOrNo.no' as done,
                            (
                                SELECT
                                    COUNT(DISTINCT create_by)
                                FROM
                                    t_course_task_report
                                WHERE
                                    group_id = tctl.id
                                AND del_flag = 0
                                AND report_status IN ('reportStatus.submit','reportStatus.review')
                            ) AS people_num
                        FROM
                            t_course_task_list tctl
                        WHERE
                            tctl.task_id =:id
                        AND tctl.del_flag = 0
                        ORDER BY tctl.create_time";
                $params = [':id' => $taskId];
                $task_list = Yii::$app->db->createCommand($sql)
                                ->bindValues($params)
                                ->queryAll();
                if($task_list)
                {
                    $report_sql = "SELECT id,report_status,submit_time,group_id FROM t_course_task_report WHERE task_id='".$taskId."' AND create_by='".$userId."' AND del_flag=0";
                    $report = Yii::$app->db->createCommand($report_sql)->queryOne();
                    if ($report) {
                        if ($report['report_status']=='reportStatus.review') {
                            $task['report_status'] = "yesOrNo.yes";
                        }
                        if ($report['report_status']=='reportStatus.back') {
                            $task['report_status'] = "reportStatus.back";
                            if (!empty($report['submit_time']) && $report['submit_time']!='0000-00-00 00:00:00') {
                                $task['deadline'] = $report['submit_time'];
                            } else {
                                $task['deadline'] = '';
                            }
                        }
                    }
                    if (!empty($report['group_id'])) {
                        foreach ($task_list as $key => $value) {
                            if ($value['id']==$report['group_id']) {
                                $task_list[$key]['done'] = "yesOrNo.yes";
                            }
                            // $report_sql = "SELECT id,report_status,submit_time FROM t_course_task_report WHERE group_id='".$value['id']."' AND create_by='".$userId."' AND del_flag=0";
                            // $report = Yii::$app->db->createCommand($report_sql)->queryOne();
                            // if($report)
                            // {
                            //     if($report['report_status']=='reportStatus.review')
                            //     {
                            //         $task['report_status'] = "yesOrNo.yes";
                            //     }
                            //     if ($report['report_status']=='reportStatus.back') {
                            //         $task['report_status'] = "reportStatus.back";
                            //         if (!empty($report['submit_time']) && $report['submit_time']!='0000-00-00 00:00:00') {
                            //             $task['deadline'] = $report['submit_time'];
                            //         } else {
                            //             $task['deadline'] = '';
                            //         }
                            //     }
                            //     $task_list[$key]['done'] = "yesOrNo.yes";
                            // }
                        }
                    }
                    $task['task_list'] = ArrayHelper::array_is_null($task_list);
                }
                else
                {
                    $task['task_list'] = [];
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $task,
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP任务详情接口
     * @param int  taskId:任务ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-02
     * @author: gaoyj
     */
    public function actionAppGetCourseTaskInfo()
    {
        $error = array();
        $taskId = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('任务ID不能为空');
        $taskListId = !empty($_REQUEST['taskListId'])?$_REQUEST['taskListId']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(!empty($taskListId))
            {
                $task_list = TCourseTaskList::find()->select('id,task_id,task_title,task_content')->where('id=:id', [':id' => $taskListId])->asArray()->one();
                if($task_list)
                {
                    $task_list['task_content'] = str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($task_list['task_content'])));
                    $task = TCourseTask::find()->select('id,task_title,task_content,task_score,group_way,end_time,task_status,task_experience,old_id')->where('id=:id', [':id' => $task_list['task_id']])->asArray()->one();
                    if($task)
                    {
                        $task['task_content'] = str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($task['task_content'])));
                        $task = ArrayHelper::array_is_null($task);
                        $task['start_time'] = date("Y-m-d H:i:s");
                        $task['task_list'] = ArrayHelper::array_is_null($task_list);
                        $result = [
                            'msg' => '查找成功',
                            'ver' => '1.5.0',
                            'data' => $task,
                            'success' => true,
                            'code' => '200'
                        ];
                    }
                    else
                    {
                        $result = [
                            'msg' => '查找失败',
                            'ver' => '1.5.0',
                            'data' => (object)array(),
                            'success' => false,
                            'code' => '400'
                        ];
                    }
                }
                else
                {
                    $result = [
                        'msg' => '查找失败',
                        'ver' => '1.5.0',
                        'data' => (object)array(),
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $task = TCourseTask::find()->select('id,task_title,task_content,task_score,group_way,end_time,task_status,task_experience')->where('id=:id', [':id' => $taskId])->asArray()->one();
                if($task)
                {
                    $task = ArrayHelper::array_is_null($task);
                    $task['start_time'] = date("Y-m-d H:i:s");
                    $task_list = TCourseTaskList::find()->select('id,task_id,task_title,task_content')->where('task_id=:id', [':id' => $taskId])->asArray()->one();
                    if($task_list)
                    {
                        $task['task_list'] = ArrayHelper::array_is_null($task_list);
                    }
                    else
                    {
                        $task['task_list'] = (object)array();
                    }
                    $result = [
                        'msg' => '查找成功',
                        'ver' => '1.5.0',
                        'data' => $task,
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '查找失败',
                        'ver' => '1.5.0',
                        'data' => (object)array(),
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP任务回答内容接口
     * @param int  taskId:任务ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-02
     * @author: gaoyj
     */
    public function actionAppGetCourseTaskReport()
    {
        $error = array();
        $taskId = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('任务ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $childId = !empty($_REQUEST['childId'])?$_REQUEST['childId']:$error[]=array('子任务ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(!empty($childId))
            {
                $sql = "select id,report_content,report_score,update_time,report_status,old_id from t_course_task_report where task_id=:taskId and group_id=:childId and create_by=:userId and del_flag=0";
                $params = [':taskId' => $taskId, ':userId' => $userId, ':childId' => $childId];
            }
            else
            {
                $sql = "select id,report_content,report_score,update_time,report_status,old_id from t_course_task_report where task_id=:taskId and create_by=:userId and del_flag=0";
                $params = [':taskId' => $taskId, ':userId' => $userId];
            }
            $report = \Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryOne();
            if($report)
            {
                $report = ArrayHelper::array_is_null($report);
                $report['report_score'] = intval($report['report_score']);
                $appraise_sql = "SELECT CASE
                                    WHEN update_time IS NULL THEN
                                        create_time
                                    ELSE
                                        update_time
                                    END AS appraise_time,appraise_content FROM t_course_task_report_appraise WHERE report_id='".$report['id']."' AND del_flag=0";
                $appraise = \Yii::$app->db->createCommand($appraise_sql)->queryOne();
                if($appraise)
                {
                    $report = array_merge($report,$appraise);
                }
                $report['report_content'] = $report['report_content'];
                $report['task_files']['image'] = array();
                $report['task_files']['video'] = array();
                $report['task_files']['audio'] = array();
                $report['task_files']['material'] = array();
                // 获取任务附件
                $sql1 = "select * from t_course_task_file where report_id='".$report['id']."' and del_flag=0";
                $task_files = Yii::$app->db->createCommand($sql1)->queryAll();
                if($task_files)
                {
                    foreach ($task_files as $value) {
                        switch ($value['mime']) {
                            case 'application/msword':
                            case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                                $type='word';
                                break;
                            case 'application/vnd.ms-excel':
                            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                                $type='excel';
                                break;
                            case 'application/vnd.ms-powerpoint':
                            case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                                $type='ppt';
                                break;
                            case 'application/pdf':
                                $type='pdf';
                                break;
                            case 'text/plain':
                                $type='txt';
                                break;
                        }
                        $file_info=array();
                        if ($value['mime'] == 'image/jpeg'||$value['mime'] == 'image/jpg'||$value['mime'] == 'image/gif'||$value['mime'] == 'image/png'||$value['mime'] == 'image/*' )
                        {
                            $file_info=array(
                                'filename'=>$value['name'],
                                'compress_uri'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',//压缩路径
                                'original_uri'=>!empty($value['image_uri']) ? Yii::$app->params['fileUrl'].$value['image_uri'] : '',//原图路径
                                'thumb_uri'=>!empty($value['thumb_uri']) ? Yii::$app->params['fileUrl'].$value['thumb_uri'] : '',//缩略图路径
                                'original'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',
                                'fid'=>$value['id']
                            );
                            $report['task_files']['image'][] = $file_info;
                        } 
                        elseif ($value['mime'] == 'video/mp4')
                        { 
                            $report['task_files']['video'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//压缩路径
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//原图路径
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//缩略图路径
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3')
                        { 
                            $report['task_files']['audio'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//压缩路径
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//原图路径
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//缩略图路径
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation'|| $value['mime'] == 'application/vnd.ms-powerpoint'|| $value['mime'] == 'text/plain'|| $value['mime'] == 'application/pdf')
                        {
                            $html_url = BaseController::getFileHtmlUrl( Yii::$app->params['fileUrl'].$value['file_uri']);
                            $report['task_files']['material'][] = array(
                                'filename'=>$value['name'],
                                'type'=>$type,
                                'original_uri'=>$html_url,
                                'original'=>$html_url,
                                'compress_uri'=>$html_url,
                                'thumb_uri'=>$html_url,
                                'fid'=>$value['id']
                            );
                        }
                    }
                }
                $result = array(
                    "msg" => "查询成功",
                    "ver" => "1.5.0",
                    'data' => $report,
                    'success' => true,
                    'code' => '200'
                );
            }
            elseif(empty($report))
            {
                $result = array(
                    "msg" => "数据为空",
                    "ver" => "1.5.0",
                    'data' => (object)array(),
                    'success' => false,
                    'code' => '404'
                );
            }
            elseif($report===false)
            {
                $result = array(
                    "msg" => "查询失败",
                    "ver" => "1.5.0",
                    'data' => (object)array(),
                    'success' => false,
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP提交任务接口
     * @param int  taskId:任务ID userId:用户ID projectId:联盟ID
     * @param int  report_content:任务内容 token:token
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-01
     * @author: gaoyj
     */
    public function actionAppSubmitCourseTask()
    {
        $error = array();
        $taskId = isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('子任务ID不能为空');
        $file_id = !empty($_REQUEST['file_id'])?$_REQUEST['file_id']:'';
        $report_id = !empty($_REQUEST['report_id'])?$_REQUEST['report_id']:'';
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $start_time = !empty($_REQUEST['start_time'])?$_REQUEST['start_time']:$error[]=array('开始时间不能为空');
        $report_content = isset($_REQUEST['report_content'])?$_REQUEST['report_content']:$error[]=array('任务内容不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => ['status' => '','old_id'=>''],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => ['status' => '','old_id'=>''],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $task = TCourseTaskList::findOne($taskId);
            if(!$task){
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => ['status' => '','old_id'=>''],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            $report_back_status = TCourseTaskReport::find()->select('report_status,submit_time')->where('task_id=:task_id and create_by=:create_by and del_flag=0',[':task_id' => $task->task_id,':create_by' => $userId])->asArray()->one();
            $status = TCourseTask::find()->where('id=:id and del_flag=0',[':id' => $task->task_id])->one();
            if ($report_back_status['report_status']=='reportStatus.back') {
                if (!empty($report_back_status['submit_time']) && $report_back_status['submit_time']!='0000-00-00 00:00:00') {
                    if (strtotime($report_back_status['submit_time']) < time()) {
                        $result = [
                            'msg' => '本次任务时间已结束！',
                            'ver' => '1.5.0',
                            'data' => ['status' => 'over','old_id'=>''],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            } else {
                if ($status) {
                    if (!empty($status->deadline) && $status->deadline!='0000-00-00 00:00:00') {
                        if (strtotime($status->deadline)<time()) {
                            $result = [
                                'msg' => '本次任务时间已结束！',
                                'ver' => '1.5.0',
                                'data' => ['status' => '','old_id'=>''],
                                'code' => '400'
                            ];
                            Yii::$app->end(json_encode($result));
                        }
                    }
                    if ($status->task_status=='activityStatus.over') {
                        $result = [
                            'msg' => '该任务已结束',
                            'ver' => '1.5.0',
                            'data' => ['status' => 'over','old_id'=>''],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                } else {
                    $result = [
                        'msg' => '该任务已结束',
                        'ver' => '1.5.0',
                        'data' => ['status' => '','old_id'=>''],
                        'code' => '602'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            $courseStatus = TCourseInfo::findOne($status->t_course_id);
            if($courseStatus)
            {
                if($courseStatus->course_status!='courseCheckStatus.release')
                {
                    $result = [
                        'msg' => '该课程已结束',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'over','old_id'=>''],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            else
            {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => ['status'=>'','old_id'=>''],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(!empty($report_id))
            {
                $transaction = \Yii::$app->db->beginTransaction();
                $model = TCourseTaskReport::find()->select('old_id')->where('id=:report_id and del_flag=0',[':report_id' => $report_id])->one();
                $res = \Yii::$app->db ->createCommand()->update('t_course_task_report',[
                            'report_content' => $report_content,
                            'report_status' => 'reportStatus.submit',
                            'update_by' => $userId,
                            'update_time' => date("Y-m-d H:i:s"),
                            ],"id='".$report_id."' and del_flag=0")
                        ->execute();
                if($res)
                {
                    if(!empty($file_id))
                    {
                        $ids = explode(',', $file_id);
                        $fileId = implode("','",$ids);
                        $sql = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$report_id."'";
                        $file_res = \Yii::$app->db->createCommand($sql)->execute();
                        $sql1 = "update t_course_task_file set del_flag = 0,report_id='".$report_id."',update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where id IN('".$fileId."')";
                        $res1 = \Yii::$app->db->createCommand($sql1)->execute();
                        if($res1)
                        {
                            $transaction->commit();
                            $result = array(
                                "msg" => "操作成功",
                                "ver" => "1.5.0",
                                'data' => ['status'=>'','old_id'=>!empty($model->old_id)?$model->old_id:''],
                                'success' => true,
                                'code' => '200'
                            );
                        }
                        else
                        {
                            $transaction->rollback();
                            $result = array(
                                "msg" => "操作失败",
                                "ver" => "1.5.0",
                                'data' => ['status'=>'','old_id'=>''],
                                'success' => false,
                                'code' => '400'
                            );
                        }
                    }
                    else
                    {
                        $sql = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$report_id."'";
                        $file_res = \Yii::$app->db->createCommand($sql)->execute();
                        $transaction->commit();
                        $result = array(
                            "msg" => "操作成功",
                            "ver" => "1.5.0",
                            'data' => ['status'=>'','old_id'=>''],
                            'success' => true,
                            'code' => '200'
                        );
                    }
                    Yii::$app->end(json_encode($result));
                }
                else
                {
                    $result = [
                        'msg' => '提交失败',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'','old_id'=>''],
                        'success' => false,
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            }
            else
            {
                $transaction = \Yii::$app->db->beginTransaction();
                // $res = \Yii::$app->db ->createCommand()->insert('t_course_task_report',[
                //             'task_id' => $task->task_id, 
                //             'group_id' => $taskId,
                //             'report_title' => $task->task_title,
                //             'report_content' => $report_content,
                //             'report_status' => 'reportStatus.submit',
                //             'create_by' => $userId,
                //             'create_time' => date("Y-m-d H:i:s"),
                //             'del_flag' => 0,
                //             ])
                //         ->execute(); 
                $model = TCourseTaskReport::find()->where('task_id=:task_id and create_by=:create_by and del_flag=0',[':task_id' => $task->task_id,':create_by' => $userId])->one();
                if($model)
                {
                    $model->group_id = $taskId;
                    $model->report_title = $task->task_title;
                    $model->report_content = $report_content;
                    $model->report_status = 'reportStatus.submit';
                    $model->update_by = $userId;
                    $model->update_time = date("Y-m-d H:i:s");
                    if($model->save())
                    {
                        $id = $model->id;
                        $file_up_flag = false;
                        if(!empty($file_id))
                        {
                            $ids = explode(',', $file_id);
                            $fileId = implode("','",$ids);
                            $sql1 = "update t_course_task_file set del_flag = 1,update_by='".$userId."',update_time='".date("Y-m-d H:i:s")."'  where report_id='".$id."'";
                            $res = \Yii::$app->db->createCommand($sql1)->execute();
                            $sql = "update t_course_task_file set report_id = '".$id."',create_by = '".$userId."'  where id in ('".$fileId."')";
                            $file_res = Yii::$app->db->createCommand($sql)->execute();
                            if($file_res){
                                $file_up_flag = true;
                            }
                        }
                        else
                        {
                            $report = \app\models\TCourseTaskFile::find()->where('report_id=:id',[':id'=>$id])->all();
                            if(!empty($report)){
                                $res = \app\models\TCourseTaskFile::updateAll(['del_flag'=>1,'update_by'=>$userId,'update_time'=>date("Y-m-d H:i:s")],['report_id'=>$id]);
                            }else{
                                $res = true;
                            }
                            if($res){
                                $file_up_flag = true;
                            }
                        }
                        if($file_up_flag)
                        {
                            $time = date("Y-m-d H:i:s");
                            $send_data = [
                                'tasksEvaluationid' => !empty($model->old_id)?$model->old_id:'',
                                'userid' => PdUtils::getOldId('t_base_user',$userId),
                                'launchCourseid' => $courseStatus->old_id,
                                'learningTasksid' => PdUtils::getOldId('t_course_task',$task->task_id),
                                'status' => '已提交',
                                'startdotime' => $start_time,
                                'gradetime' => $time,
                                'submittime' => $time,
                                'modifiedtime' => $time,
                                'bcourseid' => PdUtils::getOldIdByTid($courseStatus->id),
                                'projectid' => $projectId,
                            ];
                            @PdUtils::SaveMongoData($send_data, 'correcting');
                            $transaction->commit();
                            $result = array(
                                "msg" => "操作成功",
                                "ver" => "1.5.0",
                                'data' => ['status'=>'','old_id'=>!empty($model->old_id)?$model->old_id:''],
                                'success' => true,
                                'code' => '200'
                            );
                        }
                        else
                        {
                            $transaction->rollback();
                            $result = array(
                                "msg" => "操作失败",
                                "ver" => "1.5.0",
                                'data' => ['status'=>'','old_id'=>''],
                                'success' => false,
                                'code' => '400'
                            );
                        }
                        Yii::$app->end(json_encode($result));
                    }
                    else
                    {
                        $result = [
                            'msg' => '提交失败',
                            'ver' => '1.5.0',
                            'data' => ['status'=>'','old_id'=>''],
                            'success' => false,
                            'code' => '400'
                        ];
                    }
                }
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /*
     * 任务附件上传
     */
    public function actionAppTaskFilesInput(){
        $error = array();
        $userId = empty($_REQUEST['userId'])?$error[]=array('用户ID不能为空'):$_REQUEST['userId'];
        $courseId = empty($_REQUEST['courseId'])?$error[]=array('课程ID不能为空'):$_REQUEST['courseId'];
        if(!empty($error))
        {
            $result = array(
                "msg"=> "缺少参数",
                "ver"=> "1.5.0",
                'data'=>$error,
                'success' => false,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            if(!empty($_FILES)){
                $projectId = TCourseInfo::findOne($courseId)['project_id'];
                if(!empty($projectId)){
                    $path = 'files'.DIRECTORY_SEPARATOR.$projectId.DIRECTORY_SEPARATOR.'teach'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
                }else{
                    $path = 'files'.DIRECTORY_SEPARATOR.'teach'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
                }
                if(!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)){
                    mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
                }
                $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
                $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
                if(move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)){
                    if ($fileformat == 'mp4') {
                        exec("/usr/local/ffmpeg2/bin/ffmpeg -i " . \Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//", $res, $code);
                        if ($code == 0) {
                            $play_time = $res[0];
                        }
                    }
                    if(stristr($_FILES['files']['type'], 'image')){
                        if (ceil($_FILES['files']['size']/1024)>900) {
                            $uri2 = $path.md5($_FILES['files']["name"]. time()).'_compress_'.'.'.$fileformat;
                            $compressPath = PdUtils::ThumbImage(file_get_contents(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri), 100, 100,sprintf('%.2f',100/($_FILES['files']['size']/1024/900)/100)+0.1,\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri2);
                        } else {
                            $uri2 = $uri;
                        }
                        $uri3 = $path.md5($_FILES['files']["name"]. time()).'_thumb_'.'.'.$fileformat;
                        $thumbPath = PdUtils::ThumbImage(file_get_contents(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri), 100, 100,0,\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri3);
                        // $thumbPath = \yii\imagine\Image::thumbnail(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri, 100 , 100,\Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET)->save(Yii::getAlias(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri3),['quality' => 100]);
                    }else{ 
                        $uri2 = $uri3 = $uri;
                    }
                    $model = new TCourseTaskFile();
                    $model->id=Uuid::uuid();
                    $model->name=$_FILES['files']["name"];
                    $model->image_uri=$uri;
                    $model->thumb_uri=$uri3;
                    $model->file_uri=$uri2;
                    $model->size= $_FILES['files']["size"];
                    $model->create_by = $userId;
                    $model->create_time = date('Y-m-d H:i:s', time());
                    $model->type = $fileformat;
                    $model->mime = $_FILES['files']["type"];
                    $model->del_flag = 0;
                    if($model->validate() && $model->save())
                    {
                        $arr=array(
                                    'fid'=>$model->attributes['id'],
                                    'filename' => $_FILES['files']["name"],
                                    'type' => $_FILES['files']["type"],
                                    'size' => $_FILES['files']["size"],
                                    'url' => Yii::$app->params['fileUrl'].$uri
                                );
                        $result = array(
                            "msg"=> "保存成功",
                            "ver"=> "1.5.0",
                            'data'=> $arr,
                            'success' => true,
                            'code'=>'200'
                        );
                    }
                    else
                    {
                        $result = array(
                            "msg"=> "保存失败",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'success' => false,
                            'code'=>'400'
                        );
                    }
                }else{
                    $result = array(
                        "msg"=> "上传失败",
                        "ver"=> "1.5.0",
                        'data'=>array(),
                        'success' => false,
                        'code'=>'400'
                    );
                }
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }

    /**
     * APP查询习题列表接口（答题卡用）
     * @param int  paperId:试卷ID quizId:测验ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-12
     * @author: gaoyj
     */
    public function actionAppGetQuestionListByPaperid()
    {
        // html_entity_decode(strip_tags());
        $error = array();
        $paperId = isset($_REQUEST['paperId'])?$_REQUEST['paperId']:$error[]=array('试卷ID不能为空');
        $quizId = isset($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $resultId = !empty($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'result_id' => '',
                'start_time' => '',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'result_id' => '',
                    'start_time' => '',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
            $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
            $newArray = array();
            if($Type)
            {
                foreach ($Type as $key => $value)
                {
                    $sql = "SELECT
                            q.id,q.content,q.type,q.difficulty,tqp.score,'' as selected,q.old_id
                        FROM
                            t_quiz_question q
                        LEFT JOIN t_quiz_paper_ques_relation tqp ON q.id = tqp.ques_id
                        WHERE
                            tqp.paper_id = '".$paperId."' 
                        AND tqp.ques_type='".$value."'
                        AND tqp.del_flag = 0
                        GROUP BY
                            q.id
                        ORDER BY
                            tqp.sequence";//AND q.status='questionStatus.approved'
                        $info = Yii::$app->db->createCommand($sql)->queryAll();
                        $newArray = array_merge($newArray,$info);
                }
                if(!empty($newArray))
                {
                    if(!empty($resultId))
                    {
                        $result_sql = "SELECT ques_id FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                        $params = [':resultId' => $resultId];
                        $ques_id = Yii::$app->db->createCommand($result_sql)
                            ->bindValues($params)
                            ->queryColumn();
                        foreach ($newArray as $key =>& $value)
                        {
                            if (in_array($value['id'], $ques_id)) {
                                $sql1 = "SELECT answer FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                                $answer = Yii::$app->db->createCommand($sql1)->queryOne();
                                $value['selected'] = $answer['answer'];
                                $file_sql = "SELECT id FROM t_quiz_result_answer_file WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                                $file = Yii::$app->db->createCommand($file_sql)->queryOne();
                                if (!empty($file)) {
                                    $value['selected'] = 'yes';
                                }
                            }
//                            $value['content'] = $value['content'];
//                            $value['score'] = $value['score'];
                        }
                        // $data = TQuizResult::findOne($resultId);
                        // if($data)
                        // {
                        //     if(empty($data->begin_time))
                        //     {
                        //         $data->begin_time = date("Y-m-d H:i:s");
                        //         if (empty($data->status)) {
                        //             $data->status = 'quizResultStatus.answerIn';
                        //         }
                        //         $data->update_by = $userId;
                        //         $data->update_time = date("Y-m-d H:i:s");
                        //         if(!$data->save())
                        //         {
                        //             $result = [
                        //                 'msg' => '答题失败',
                        //                 'ver' => '1.5.0',
                        //                 'result_id' => '',
                        //                 'start_time' => '',
                        //                 'data' => [],
                        //                 'code' => '400'
                        //             ];
                        //             Yii::$app->end(json_encode($result));
                        //         }
                        //     }
                        //     $result_id = $data->id;
                        // }
                    }
                    $newArray = ArrayHelper::array_is_null($newArray);
                    $allData = array();
                    foreach ($newArray as $in){
                        $sql="select id,answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$in['id']."' ORDER BY answ_code";
                        $answers = Yii::$app->db->createCommand($sql)->queryAll();
                        // if ($in['type']=='questionType.fillIn') {
                        //     $a = '';
                        //     foreach ($answers as $k => $v) {
                        //         if ($v['answ_code']=='A') {
                        //             $a =  "空1";
                        //         } elseif ($v['answ_code']=='B'){
                        //             $a =  "空2";
                        //         } elseif ($v['answ_code']=='C'){
                        //             $a =  "空3";
                        //         } elseif ($v['answ_code']=='D'){
                        //             $a =  "空4";
                        //         } elseif ($v['answ_code']=='E'){
                        //             $a =  "空5";
                        //         } elseif ($v['answ_code']=='F'){
                        //             $a =  "空6";
                        //         } elseif ($v['answ_code']=='G'){
                        //             $a =  "空7";
                        //         } elseif ($v['answ_code']=='H'){
                        //             $a =  "空8";
                        //         }
                        //         $answers[$k]['answ_code'] = $a;
                        //     }
                        // }
                        $allData[]= array_merge($in,array('answers'=>ArrayHelper::array_is_null($answers)));
                    }
                    $result = [
                        'msg' => '查找成功',
                        'ver' => '1.5.0',
                        'result_id' => $resultId,
                        'start_time' => date("Y-m-d H:i:s"),
                        'data' => $allData,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                elseif(empty($newArray))
                {
                    $result = [
                        'msg' => '数据为空',
                        'ver' => '1.5.0',
                        'result_id' => '',
                        'start_time' => '',
                        'data' => [],
                        'code' => '404'
                    ];
                }
                elseif($newArray===false)
                {
                    $result = [
                        'msg' => '查找失败',
                        'ver' => '1.5.0',
                        'result_id' => '',
                        'start_time' => '',
                        'data' => [],
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'result_id' => '',
                    'start_time' => '',
                    'data' => [],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP查询习题列表接口（答题用）
     * @param int  paperId:试卷ID quizId:测验ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-09-26
     * @author: gaoyj
     */
    public function actionAppGetQuestionList()
    {
        // html_entity_decode(strip_tags());
        $error = array();
        $paperId = isset($_REQUEST['paperId'])?$_REQUEST['paperId']:$error[]=array('试卷ID不能为空');
        $quizId = isset($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $resultId = !empty($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:'';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'result_id' => '',
                'start_time' => '',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
//            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
//            if(empty($device))
//            {
//                $result = [
//                    'msg' => 'Token失效',
//                    'ver' => '1.5.0',
//                    'result_id' => '',
//                    'start_time' => '',
//                    'data' => [],
//                    'code' => '900'
//                ];
//                Yii::$app->end(json_encode($result));
//            }
            $data = TQuizResult::findOne($resultId);
            if ($data->status=='quizResultStatus.backed') {
                if (!empty($data->back_result_end_time && $data->back_result_end_time!='0000-00-00 00:00:00')) {
                    if (strtotime($data->back_result_end_time)<time()) {
                        $result = [
                            'msg' => '最晚答题时间已过',
                            'ver' => '1.5.0',
                            'result_id' => '',
                            'start_time' => '',
                            'data' => [],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            }
            $quiz = TQuizInfo::find()->select('begin_time,result_end_time')->where('id=:id and del_flag=0',[':id'=>$quizId])->asArray()->one();
            if (!empty($quiz['begin_time'])) {
                if (strtotime($quiz['begin_time'])>time()) {
                    $result = [
                        'msg' => '未到开始答题时间！',
                        'ver' => '1.5.0',
                        'result_id' => '',
                        'start_time' => '',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            if ($data->status!='quizResultStatus.backed') {
                if (!empty($quiz['result_end_time']) && $quiz['result_end_time']!='0000-00-00 00:00:00') {
                    if (strtotime($quiz['result_end_time'])<time()) {
                        $result = [
                            'msg' => '本次测验时间已结束，请联系您的老师！',
                            'ver' => '1.5.0',
                            'result_id' => '',
                            'start_time' => '',
                            'data' => [],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            }
            $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
            $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
            $newArray = array();
            if($Type)
            {
                foreach ($Type as $key => $value)
                {
                    $sql = "SELECT
                            q.id,q.content,q.type,q.difficulty,tqp.score,'' as selected,q.old_id
                        FROM
                            t_quiz_question q
                        LEFT JOIN t_quiz_paper_ques_relation tqp ON q.id = tqp.ques_id
                        WHERE
                            tqp.paper_id = '".$paperId."' 
                        AND tqp.ques_type='".$value."'
                        AND tqp.del_flag = 0
                        GROUP BY
                            q.id
                        ORDER BY
                            tqp.sequence"; //AND q.status='questionStatus.approved'
                        $info = Yii::$app->db->createCommand($sql)->queryAll();
                        $newArray = array_merge($newArray,$info);
                }
                if(!empty($newArray))
                {
                    $newArray = ArrayHelper::array_is_null($newArray);
                    if(!empty($resultId))
                    {
                        $result_sql = "SELECT ques_id FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                        $params = [':resultId' => $resultId];
                        $ques_id = Yii::$app->db->createCommand($result_sql)
                            ->bindValues($params)
                            ->queryColumn();
                        foreach ($newArray as $key =>& $value)
                        {
                            if (in_array($value['id'], $ques_id)) {
                                $sql1 = "SELECT answer FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                                $answer = Yii::$app->db->createCommand($sql1)->queryOne();
                                $value['selected'] = $answer['answer'];
                                $file_sql = "SELECT CASE
                                                WHEN image_uri = '' THEN
                                                    ''
                                                ELSE
                                                    CONCAT(
                                                        '".Yii::$app->params['fileUrl']."',
                                                        image_uri
                                                    )
                                                END AS image_uri,id,name FROM t_quiz_result_answer_file WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                                $file = Yii::$app->db->createCommand($file_sql)->queryAll();
                                $value['file'] = ArrayHelper::array_is_null($file);
                            } else {
                                $value['file'] = [];
                            }
                            // $value['content'] = $value['content'];
                            // $value['score'] = $value['score'];
                        }
                        if($data)
                        {
                            if(empty($data->begin_time))
                            {
                                $data->begin_time = date("Y-m-d H:i:s");
                                if (empty($data->status)) {
                                    $data->status = 'quizResultStatus.answerIn';
                                }
                                $data->update_by = $userId;
                                $data->update_time = date("Y-m-d H:i:s");
                                if(!$data->save())
                                {
                                    $result = [
                                        'msg' => '答题失败',
                                        'ver' => '1.5.0',
                                        'result_id' => '',
                                        'start_time' => '',
                                        'data' => [],
                                        'code' => '400'
                                    ];
                                    Yii::$app->end(json_encode($result));
                                }
                            }
                            $result_id = $data->id;
                        }
                    }
                    
                    $allData = array();
                    foreach ($newArray as $in){
                        $sql="select id,answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$in['id']."' ORDER BY answ_code";
                        $answers = Yii::$app->db->createCommand($sql)->queryAll();
                        // if ($in['type']=='questionType.fillIn') {
                        //     $a = '';
                        //     foreach ($answers as $k => $v) {
                        //         if ($v['answ_code']=='A') {
                        //             $a =  "空1";
                        //         } elseif ($v['answ_code']=='B'){
                        //             $a =  "空2";
                        //         } elseif ($v['answ_code']=='C'){
                        //             $a =  "空3";
                        //         } elseif ($v['answ_code']=='D'){
                        //             $a =  "空4";
                        //         } elseif ($v['answ_code']=='E'){
                        //             $a =  "空5";
                        //         } elseif ($v['answ_code']=='F'){
                        //             $a =  "空6";
                        //         } elseif ($v['answ_code']=='G'){
                        //             $a =  "空7";
                        //         } elseif ($v['answ_code']=='H'){
                        //             $a =  "空8";
                        //         }
                        //         $answers[$k]['answ_code'] = $a;
                        //     }
                        // }
                        $allData[]= array_merge($in,array('answers'=>ArrayHelper::array_is_null($answers)));
                    }
                    $result = [
                        'msg' => '查找成功',
                        'ver' => '1.5.0',
                        'result_id' => !empty($resultId)?$resultId:$result_id,
                        'start_time' => date("Y-m-d H:i:s"),
                        // 'begin_time' => !empty($quiz['begin_time']) ? $quiz['begin_time'] : '',
                        // 'result_end_time' => !empty($quiz['result_end_time']) ? $quiz['result_end_time'] : '',
                        'data' => $allData,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                elseif(empty($newArray))
                {
                    $result = [
                        'msg' => '数据为空',
                        'ver' => '1.5.0',
                        'result_id' => '',
                        'start_time' => '',
                        'data' => [],
                        'code' => '404'
                    ];
                }
                elseif($newArray===false)
                {
                    $result = [
                        'msg' => '查找失败',
                        'ver' => '1.5.0',
                        'result_id' => '',
                        'start_time' => '',
                        'data' => [],
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'result_id' => '',
                    'start_time' => '',
                    'data' => [],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP保存答案（每次一道题）接口
     * @param int  resultId:答题卡ID quesId:问题ID userId:用户ID token:token projectId:联盟ID
     * @param string  correct_answer:正确答案 answer:答题内容 score:分值
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-13
     * @author: gaoyj
     */
    public function actionAppSaveOneAnswer(){
        $error = array();
        $resultId = !empty($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $quesId = !empty($_REQUEST['quesId'])?$_REQUEST['quesId']:$error[]=array('问题ID不能为空');
        // $correct_answer = !empty($_REQUEST['correct_answer'])?$_REQUEST['correct_answer']:'';
        $answer = !empty($_REQUEST['answer'])?$_REQUEST['answer']:'';
        $score = !empty($_REQUEST['score'])?$_REQUEST['score']:$error[]=array('分值不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $file_id = isset($_REQUEST['file_id'])?$_REQUEST['file_id']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = !empty($_REQUEST['token'])?$_REQUEST['token']:'';
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => ['status'=>''],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
//            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
//            if (empty($device)) {
//                $result = [
//                    'msg' => 'Token失效',
//                    'ver' => '1.5.0',
//                    'data' => ['status'=>''],
//                    'code' => '900'
//                ];
//                Yii::$app->end(json_encode($result));
//            }
            $quizId = TQuizResult::findOne($resultId);
            $status = TQuizInfo::find()->where('id=:id and del_flag=0',[':id' => $quizId->quiz_id])->one();
            if ($quizId->status=='quizResultStatus.backed') {
                if (!empty($quizId->back_result_end_time) && $quizId->back_result_end_time!='0000-00-00 00:00:00') {
                    if (strtotime($quizId->back_result_end_time)<time()) {
                        $result = [
                            'msg' => '本次测验时间已结束！',
                            'ver' => '1.5.0',
                            'data' => ['status'=>'over'],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            } else {
                if ($status) {
                    if (!empty($status->result_end_time)) {
                        if (strtotime($status->result_end_time)<time()) {
                            $result = [
                                'msg' => '本次测验时间已结束，请联系您的老师！',
                                'ver' => '1.5.0',
                                'data' => ['status'=>'over'],
                                'code' => '400'
                            ];
                            Yii::$app->end(json_encode($result));
                        }
                    }
                    if ($status->quiz_status=='activityStatus.over') {
                        $result = [
                            'msg' => '该测验已结束',
                            'ver' => '1.5.0',
                            'data' => ['status'=>'over'],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                } else {
                    $result = [
                        'msg' => '该测验已被删除',
                        'ver' => '1.5.0',
                        'data' => ['status'=>''],
                        'code' => '602'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            $courseStatus = TCourseInfo::findOne($status->t_course_id);
            if ($courseStatus) {
                if($courseStatus->course_status!='courseCheckStatus.release')
                {
                    $result = [
                        'msg' => '该课程已结束',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'over'],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            } else {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => ['status'=>''],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            if($quizId->status=="quizResultStatus.marking" || $quizId->status=="quizResultStatus.submitted" || $quizId->status=="quizResultStatus.marked"){
                $result = [
                    'msg' => '已交卷',
                    'ver' => '1.5.0',
                    'data' => ['status'=>''],
                    'code' => '603'
                ];
                Yii::$app->end(json_encode($result));
            }
            $transaction = \Yii::$app->db->beginTransaction();
            try {  
                $resultAnswer = TQuizResultAnswer::find()->where(['result_id'=>$resultId,'ques_id'=>$quesId,'del_flag'=>0])->one();
                $ques_sql = "SELECT type,old_id FROM t_quiz_question WHERE id='".$quesId."' AND del_flag=0";
                $quesType = Yii::$app->db->createCommand($ques_sql)->queryOne();
                if($quesType['type']=='questionType.shortAnswer' || $quesType['type']=='questionType.discuss')
                {
                    $correct_answer = array();
                }
                elseif($quesType['type']=='questionType.fillIn')
                {
                    $correct_sql = "SELECT answ_code,answ_content FROM t_quiz_question_answer WHERE ques_id='".$quesId."' AND is_right='yesOrNo.yes' AND del_flag=0 ORDER BY answ_code";
                    $correct_answers = Yii::$app->db->createCommand($correct_sql)->queryAll();
                    $str = '';
                    foreach ($correct_answers as $key => $value) {
                        $str.=$value['answ_code'].'='.$value['answ_content'].'&&';
                    }
                    $correct_answer = rtrim($str,'&&');
                }
                else
                {
                    $correct_sql = "SELECT answ_code FROM t_quiz_question_answer WHERE ques_id='".$quesId."' AND is_right='yesOrNo.yes' AND del_flag=0 ORDER BY answ_code";
                    $correct_answers = Yii::$app->db->createCommand($correct_sql)->queryColumn();
                    if(!empty($correct_answers))
                    {
                        $correct_answer = implode(',', $correct_answers);
                    }
                }
                if(empty($resultAnswer))
                {
                    $resultAnswer = new TQuizResultAnswer();
                    $resultAnswer->id = Uuid::uuid();
                    $resultAnswer->result_id = $resultId;
                    $resultAnswer->ques_id = $quesId;
                    $resultAnswer->create_by = $userId;
                    $resultAnswer->create_time = date("Y-m-d H:i:s");
                    // $res = \Yii::$app->db ->createCommand()->insert('t_quiz_result_answer',[
                    //         'id' => Uuid::uuid(),
                    //         'result_id' => $resultId, 
                    //         'ques_id' => $quesId,
                    //         'is_correct' => !empty($correct_answer)?($correct_answer==$answer?'yesOrNo.yes':'yesOrNo.no'):'yesOrNo.yes',
                    //         'answer' => $answer,
                    //         'points_awarded' => !empty($correct_answer)?$correct_answer==$answer?$score:0:'',
                    //         'answer_time' => date("Y-m-d H:i:s"),
                    //         'create_by' => $userId,
                    //         'create_time' => date("Y-m-d H:i:s"),
                    //         'del_flag' => 0,
                    //         ])
                    //     ->execute();
                }
                else
                {
                    $resultAnswer->update_by = $userId;
                    $resultAnswer->update_time = date("Y-m-d H:i:s");
                }
                if($quesType['type']=='questionType.singleChoice'  || $quesType['type']=='questionType.yesOrNo'){
                    $resultAnswer->answer = $answer;
                    $resultAnswer->is_correct = !empty($correct_answer)?($correct_answer==$answer?'yesOrNo.yes':'yesOrNo.no'):'yesOrNo.yes';
                    if($resultAnswer->is_correct=='yesOrNo.yes'){
                        $resultAnswer->points_awarded = $score;
                        $resultAnswer->answer_right = $answer;
                    }else{
                        $resultAnswer->points_awarded = '';
                        $resultAnswer->answer_right ='';
                    }
                }elseif($quesType['type']=='questionType.moreChoice'){
                    $answer = explode(',', $answer);
                    asort($answer);
                    $answer = implode(',', $answer);
                    $resultAnswer->answer = $answer;
                    $resultAnswer->is_correct = !empty($correct_answer)?($correct_answer==$answer?'yesOrNo.yes':'yesOrNo.no'):'yesOrNo.yes';
                    $answers = explode(',', $answer);
                    $str = '';
                    foreach ($answers as $key => $value) {
                        if(in_array($value, $correct_answers)){
                            $str .= $value.',';
                        }
                    }
                    $resultAnswer->answer_right = rtrim($str,',');
                    if($resultAnswer->is_correct=='yesOrNo.yes'){
                        $resultAnswer->points_awarded = $score;
                    }else{
                        $resultAnswer->points_awarded = '';
                    }
                }elseif($quesType['type']=='questionType.fillIn'){
                    $resultAnswer->answer = $answer;
                    $resultAnswer->is_correct = 'yesOrNo.yes';
                    $correct = explode('&&', $correct_answer);//正确答案
                    $answers = explode('&&', $answer);
                    //每个空的分数
                    // $fillInSingleScore = round($score/count($correct_answers),1);
                    $str = '';
                    // $points_awarded = 0;
                    foreach ($answers as $key => $value) {
                        if(in_array(trim($value,''),$correct)){
                            $str .= $value.'&&';
                            // $points_awarded += $fillInSingleScore;
                        }
                    }
                    $resultAnswer->answer_right = rtrim($str,'&&');//做对的答案
                    $resultAnswer->points_awarded = '';
                    // $resultAnswer->points_awarded = $points_awarded;
                    // if(!empty($resultAnswer->answer_right)){
                    //     $answerRightCount = count(explode('&&', $resultAnswer->answer_right));
                    //     if(count($correct_answers)==$answerRightCount){
                    //         $resultAnswer->points_awarded = $score;
                    //     }
                    // }
                    // if($resultAnswer->points_awarded>$score){
                    //     $resultAnswer->points_awarded = $score;
                    // }
                }else{
                    $resultAnswer->points_awarded = '';
                    $resultAnswer->answer = $answer;
                    $resultAnswer->is_correct = 'yesOrNo.yes';
                }
                $resultAnswer->answer_time = date('Y-m-d H:i:s');
                $resultAnswer->del_flag = 0;    
                if($resultAnswer->validate() && $resultAnswer->save()){
                    $fileModel = \app\models\TQuizResultAnswerFile::updateAll(['del_flag'=>1,'update_by'=>$userId,'update_time'=>date('Y-m-d H:i:s')],['result_id'=>$resultId,'ques_id'=>$quesId]);
                    if (!empty($file_id)) {
                        $file_ids = implode("','",explode(',', $file_id));
                        $file_sql = "UPDATE t_quiz_result_answer_file SET result_id='".$resultId."',del_flag=0 WHERE id IN ('".$file_ids."')";
                        $file_res = Yii::$app->db->createCommand($file_sql)->execute();
                    }
                    $transaction->commit();
                    $result = [
                        'msg' => '保存成功',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'','old_id'=>!empty($quesType['old_id'])?$quesType['old_id']:''],
                        'success' => true,
                        'code' => '200'
                    ];
                }else{
                    $transaction->rollback();
                    $result = [
                        'msg' => '保存失败',
                        'ver' => '1.5.0',
                        'data' => ['status'=>''],
                        'success' => false,
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $transaction->rollback();
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => ['status'=>''],
                    'success' => false,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /**
     * APP提交答案接口
     * @param int  resultId:答题卡ID quizId:测验ID userId:用户ID token:token projectId:联盟ID
     * @param string  paperType:试卷类型 ques_num:总题数
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-13
     * @author: gaoyj
     */
    public function actionAppSubmitAnswer()
    {
        $error = array();
        $resultId = !empty($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $quizId = !empty($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $paperType = !empty($_REQUEST['paperType'])?$_REQUEST['paperType']:$error[]=array('试卷类型不能为空');
        $ques_num = isset($_REQUEST['ques_num'])?$_REQUEST['ques_num']:$error[]=array('总题数不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $start_time = !empty($_REQUEST['start_time'])?$_REQUEST['start_time']:$error[]=array('开始时间不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:'';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => ['status'=>'','old_id'=>''],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
//            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
//            if(empty($device))
//            {
//                $result = [
//                    'msg' => 'Token失效',
//                    'ver' => '1.5.0',
//                    'data' => ['status'=>'','old_id'=>''],
//                    'code' => '900'
//                ];
//                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
//            }
            $status = TQuizInfo::find()->where('id=:id and del_flag=0',[':id' => $quizId])->one();
            if($status)
            {
                // if($status->quiz_status=='activityStatus.over')
                // {
                //     $result = [
                //         'msg' => '该测验已结束',
                //         'ver' => '1.5.0',
                //         'data' => ['status'=>'over','old_id'=>$status->old_id],
                //         'code' => '400'
                //     ];
                //     Yii::$app->end(json_encode($result));
                // }
            }
            else
            {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => ['status'=>'','old_id'=>''],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            $courseStatus = TCourseInfo::findOne($status->t_course_id);
            if($courseStatus)
            {
                if($courseStatus->course_status!='courseCheckStatus.release')
                {
                    $result = [
                        'msg' => '该课程已结束',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'over','old_id'=>$status->old_id],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            else
            {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => ['status'=>'','old_id'=>$status->old_id],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            $resultStatus = TQuizResult::find()->select('status,back_result_end_time')->where('id=:id',[':id'=>$resultId])->asArray()->one();
            if($resultStatus['status']=="quizResultStatus.marking" || $resultStatus['status']=="quizResultStatus.submitted" || $resultStatus['status']=="quizResultStatus.marked"){
                $result = [
                    'msg' => '已交卷',
                    'ver' => '1.5.0',
                    'data' => ['status'=>'','old_id'=>$status->old_id],
                    'code' => '603'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($resultStatus['status']=='quizResultStatus.backed') {
                if (!empty($resultStatus['back_result_end_time']) && $resultStatus['back_result_end_time']!='0000-00-00 00:00:00') {
                    if (strtotime($resultStatus['back_result_end_time']) < time()) {
                        $result = [
                            'msg' => '本次测验时间已结束！',
                            'ver' => '1.5.0',
                            'data' => ['status'=>'over'],
                            'code' => '400'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            }
            $time = date('Y-m-d H:i:s');
            $answerQuestion_sql = "select ques_id from t_quiz_result_answer where result_id=:resultId and del_flag=0";
            $answerQuestion = \Yii::$app->db->createCommand($answerQuestion_sql)->bindValue(':resultId',$resultId)->queryColumn();
            //查询本卷的试题id
            $paper = \app\models\TQuizPaperRelation::find()->where('quiz_id=:qid and del_flag=:d',[':qid'=>$quizId,':d'=>0])->one();
            $paperQuestion_sql = "select a.ques_id from t_quiz_paper_ques_relation a left join t_quiz_question b on a.ques_id=b.id where a.paper_id='".$paper->paper_id."' and a.del_flag=0 and b.del_flag=0";
            $paperQuestion = \Yii::$app->db->createCommand($paperQuestion_sql)->queryColumn();
            //查询学员未答题的试题id
            $incompleteQuestion = array_diff($paperQuestion, $answerQuestion);
            $resultAnswerFlag = true;
            $transaction = \Yii::$app->db->beginTransaction();
            if(!empty($incompleteQuestion)){
                //插入学员答题卡的答案表
                foreach($incompleteQuestion as $v){
                    $resultAnswer = new TQuizResultAnswer();
                    $resultAnswer->id = \Faker\Provider\Uuid::uuid();
                    $resultAnswer->result_id = $resultId;
                    $resultAnswer->ques_id = $v;
                    $resultAnswer->is_correct = 'yesOrNo.no';
                    $resultAnswer->answer = '';
                    $resultAnswer->answer_right = '';
                    $resultAnswer->points_awarded = '';
                    $resultAnswer->answer_time = $time;
                    $resultAnswer->create_by = $userId;
                    $resultAnswer->create_time = $time;
                    $resultAnswer->del_flag = 0;
                    $resultAnswerRes = $resultAnswer ->save();
                    if($resultAnswerRes !=false){
                        $resultAnswerFlag = true;
                    }else{
                        $resultAnswerFlag = false;
                        break;
                    }     
                } 
            }
            if($resultAnswerFlag){
                $transaction->commit();
            }else{
                $transaction->rollback();
                $result = [
                    'msg' => '提交失败',
                    'ver' => '1.5.0',
                    'data' => ['status'=>'','old_id'=>$status->old_id],
                    'success' => false,
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            $model = TQuizResult::findOne($resultId);
            if($paperType=='paperType.subjective')
            {
                // $sql = "SELECT COUNT(*) as answer_ques_num FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                // $params = [':resultId' => $resultId];
                // $answer_ques_num = \Yii::$app->db->createCommand($sql)
                //             ->bindValues($params)
                //             ->queryScalar();

                $model->quiz_id = $quizId;
                $model->end_time = date("Y-m-d H:i:s");
                $model->status = 'quizResultStatus.submitted';
                $model->answer_ques_num = count($answerQuestion);
                $model->total_ques_num = count($paperQuestion);
                $model->score = '';
                $model->is_invalid = 'yesOrNo.yes';
                $model->is_evaluated = '';
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s");
                if($model->validate() && $model->save())
                {
                    $time = date("Y-m-d H:i:s");
                    $send_data = [
                        'tasksEvaluationid' => !empty($model->old_id)?$model->old_id:'',
                        'userid' => PdUtils::getOldId('t_base_user',$userId),
                        'launchCourseid' => $courseStatus->old_id,
                        'learningTasksid' => $status->old_id,
                        'status' => '已提交',
                        'startdotime' => $start_time,
                        'gradetime' => $time,
                        'submittime' => $time,
                        'modifiedtime' => $time,
                        'bcourseid' => PdUtils::getOldIdByTid($courseStatus->id),
                        'projectid' => $projectId,
                    ];
                    @PdUtils::SaveMongoData($send_data, 'correcting');
                    $result = [
                        'msg' => '提交成功',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'','old_id'=>$status->old_id],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '提交失败',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'','old_id'=>$status->old_id],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $sql = "SELECT SUM(points_awarded) as score FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                $params = [':resultId' => $resultId];
                $answer = \Yii::$app->db->createCommand($sql)
                            ->bindValues($params)
                            ->queryOne();
                $model->quiz_id = $quizId;
                $model->end_time = date("Y-m-d H:i:s");
                $model->status = 'quizResultStatus.marked';
                $model->score = $answer['score'];
                $model->answer_ques_num = count($answerQuestion);
                $model->total_ques_num = count($paperQuestion);
                $model->is_invalid = 'yesOrNo.yes';
                $model->is_evaluated = 'quizResultStatus.marked';
                $model->update_by = $userId;
                $model->update_time = date("Y-m-d H:i:s");
                if($model->validate() && $model->save())
                {
                    $paperId = TQuizPaperRelation::find()->where('quiz_id=:quizId',[':quizId' => $quizId])->one()->paper_id;
                    $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
                    $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
                    $result_answer = array();
                    if($Type)
                    {
                        foreach ($Type as $key => $value)
                        {
                            $sql = "SELECT
                                    q.id,q.type,tqp.score as totalScore,'' as is_correct
                                FROM
                                    t_quiz_question q
                                LEFT JOIN t_quiz_paper_ques_relation tqp ON q.id = tqp.ques_id
                                WHERE
                                    tqp.paper_id = '".$paperId."' 
                                AND tqp.ques_type='".$value."'
                                AND tqp.del_flag = 0
                                AND q.del_flag = 0
                                GROUP BY
                                    q.id
                                ORDER BY
                                    tqp.sequence"; //AND q.status='questionStatus.approved'
                                $info = Yii::$app->db->createCommand($sql)->queryAll();
                                $result_answer = array_merge($result_answer,$info);
                        }
                    }
                    // $paperId = TQuizPaperRelation::find()->where('quiz_id=:quizId',[':quizId' => $quizId])->one()->paper_id;
                    // $sql = "SELECT
                    //             q.id,q.type,'' as is_correct,tqp.score as totalScore
                    //         FROM
                    //             t_quiz_paper_ques_relation tqp
                    //         LEFT JOIN t_quiz_question q ON q.id = tqp.ques_id
                    //         WHERE
                    //             tqp.paper_id = '".$paperId."'
                    //         AND q.status='questionStatus.approved'
                    //         AND tqp.del_flag = 0
                    //         AND q.del_flag = 0
                    //         GROUP BY
                    //             q.id
                    //         ORDER BY
                    //             tqp.sequence";
                    // $result_answer = \Yii::$app->db->createCommand($sql)->queryAll();
                    if($result_answer)
                    {
                        $result_answer = ArrayHelper::array_is_null($result_answer);
                        $result_sql = "SELECT ques_id FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                        $params = [':resultId' => $resultId];
                        $ques_id = Yii::$app->db->createCommand($result_sql)
                            ->bindValues($params)
                            ->queryColumn();
                        foreach ($result_answer as $key => $value)
                        {
                            if(in_array($value['id'], $ques_id))
                            {
                                $sql1 = "SELECT is_correct,points_awarded FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                                $is_correct = Yii::$app->db->createCommand($sql1)->queryOne();
                                $result_answer[$key]['is_correct'] = $is_correct['is_correct'];
                                $result_answer[$key]['score'] = !empty($is_correct['points_awarded'])?$is_correct['points_awarded']:'0.00';
                            }
                            else
                            {
                                $result_answer[$key]['score'] = "0.00";
                            }
                        }
                        $data['evaluated_time'] = date("Y-m-d H:i:s");
                        $data['answer'] = $result_answer;
                        $data['score'] = !empty($answer['score'])?$answer['score']:'0.00';
                        $data['status'] = '';
                        $data['old_id'] = $status->old_id;
                        $quiz_name = TQuizInfo::findOne($quizId);
                        if($quiz_name)
                        {
                            $data['quiz_name'] = $quiz_name->quiz_name;
                        }
                    }
                    $time = date("Y-m-d H:i:s");
                    $send_data = [
                        'tasksEvaluationid' => !empty($model->old_id)?$model->old_id:'',
                        'userid' => PdUtils::getOldId('t_base_user',$userId),
                        'launchCourseid' => $courseStatus->old_id,
                        'learningTasksid' => $status->old_id,
                        'status' => '已提交',
                        'startdotime' => $start_time,
                        'gradetime' => $time,
                        'submittime' => $time,
                        'modifiedtime' => $time,
                        'bcourseid' => PdUtils::getOldIdByTid($courseStatus->id),
                        'projectid' => $projectId,
                    ];
                    @PdUtils::SaveMongoData($send_data, 'correcting');
                    $result = [
                        'msg' => '提交成功',
                        'ver' => '1.5.0',
                        'data' => $data,
                        'success' => true,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                else
                {
                    $result = [
                        'msg' => '提交失败',
                        'ver' => '1.5.0',
                        'data' => ['status'=>'','old_id'=>$status->old_id],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }
    /**
     * APP提交答案接口
     * @param int  resultId:答题卡ID quizId:测验ID userId:用户ID token:token projectId:联盟ID
     * @param string  paperType:试卷类型 ques_num:总题数
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-13
     * @author: gaoyj
     */
    public function actionAppSubmitQuizAnswer(){
        $error = array();
        $quizId = !empty($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $quesId = !empty($_REQUEST['quesId'])?$_REQUEST['quesId']:$error[]=array('习题ID不能为空');
        $answer = !empty($_REQUEST['answer'])?$_REQUEST['answer']:$error[]=array('回答选项不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $start_time = !empty($_REQUEST['start_time'])?$_REQUEST['start_time']:$error[]=array('开始时间不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if (empty($device)) {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $resultStatus = TQuizResult::find()->select('id,status')->where('quiz_id=:quizId and create_by=:userId and del_flag=0',[':quizId'=>$quizId,':userId'=>$userId])->asArray()->one();
            $status = TQuizInfo::find()->where('id=:id and del_flag=0',[':id' => $quizId])->one();
            if (!$status) {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            $courseStatus = TCourseInfo::findOne($status->t_course_id);
            if ($courseStatus) {
                if ($courseStatus->course_status!='courseCheckStatus.release') {
                    $result = [
                        'msg' => '该课程已结束',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            } else {
                $result = [
                    'msg' => '参数错误',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '602'
                ];
                Yii::$app->end(json_encode($result));
            }
            if($resultStatus['status']=="quizResultStatus.marking" || $resultStatus['status']=="quizResultStatus.submitted" || $resultStatus['status']=="quizResultStatus.marked"){
                $result = [
                    'msg' => '已交卷',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '603'
                ];
                Yii::$app->end(json_encode($result));
            }
            $correct_sql = "SELECT answ_code FROM t_quiz_question_answer WHERE ques_id='".$quesId."' AND is_right='yesOrNo.yes' AND del_flag=0 ORDER BY answ_code";
            $correct_answers = Yii::$app->db->createCommand($correct_sql)->queryColumn();
            if (!empty($correct_answers)) {
                $correct_answer = implode(',', $correct_answers);
            }
            $time = date('Y-m-d H:i:s');
            //插入学员答题卡的答案表
            $res = TQuizResultAnswer::find()->where('result_id=:result_id and ques_id=:quesId and del_flag=0',[':result_id'=>$resultStatus['id'],':quesId'=>$quesId])->asArray()->one();
            if (empty($res)) {
                $resultAnswer = new TQuizResultAnswer();
                $resultAnswer->id = \Faker\Provider\Uuid::uuid();
                $resultAnswer->result_id = $resultStatus['id'];
                $resultAnswer->ques_id = $quesId;
                $resultAnswer->answer = $answer;
                if ($correct_answer==$answer) {
                    $resultAnswer->is_correct = 'yesOrNo.yes';
                    $resultAnswer->answer_right = $answer;
                } else {
                    $resultAnswer->is_correct = 'yesOrNo.no';
                    $resultAnswer->answer_right = '';
                }
                $resultAnswer->points_awarded = 0;
                $resultAnswer->answer_time = $time;
                $resultAnswer->create_by = $userId;
                $resultAnswer->create_time = $time;
                $resultAnswer->del_flag = 0;
                $resultAnswerRes = $resultAnswer ->save();
                if (!$resultAnswerRes) {
                    $result = [
                        'msg' => '提交失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }    
            }
            $model = TQuizResult::findOne($resultStatus['id']);
            $model->quiz_id = $quizId;
            $model->end_time = $time;
            $model->status = 'quizResultStatus.marked';
            $model->score = 0;
            $model->answer_ques_num = 1;
            $model->total_ques_num = 1;
            $model->is_invalid = 'yesOrNo.yes';
            $model->is_evaluated = 'quizResultStatus.marked';
            $model->update_by = $userId;
            $model->update_time = $time;
            if ($model->validate() && $model->save()) {
                // $send_data = [
                //     'tasksEvaluationid' => !empty($model->old_id)?$model->old_id:'',
                //     'userid' => PdUtils::getOldId('t_base_user',$userId),
                //     'launchCourseid' => $courseStatus->old_id,
                //     'learningTasksid' => $status->old_id,
                //     'status' => '已提交',
                //     'startdotime' => $start_time,
                //     'gradetime' => $time,
                //     'submittime' => $time,
                //     'modifiedtime' => $time,
                //     'bcourseid' => PdUtils::getOldIdByTid($courseStatus->id),
                //     'projectid' => $projectId,
                // ];
                // @PdUtils::SaveMongoData($send_data, 'correcting');
                $result = [
                    'msg' => '提交成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '提交失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP学生查看答题记录接口
     * @param int  resultId:答题卡ID quizId:测验 token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-25
     * @author: gaoyj
     */
    public function actionAppGetQuizAnswerRecord()
    {
        $error = array();
        $quizId = !empty($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $resultId = !empty($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            $r_sql = "SELECT * FROM t_quiz_result WHERE id=:resultId";
            $record = Yii::$app->db->createCommand($r_sql)->bindValue(':resultId',$resultId)->queryOne();
            $paper_id = TQuizPaperRelation::find()->select('paper_id')->where('quiz_id=:quizId',[':quizId' => $quizId])->one();
            $paperId = $paper_id->paper_id;
            $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
            $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
            $result_answer = array();
            foreach ($Type as $key => $val)
            {
                $sql = "SELECT
                            q.id,q.type,'' as is_correct,tqp.score as totalScore
                        FROM
                            t_quiz_paper_ques_relation tqp
                        LEFT JOIN t_quiz_question q ON q.id = tqp.ques_id
                        WHERE
                            tqp.paper_id = '".$paperId."' 
                        AND tqp.ques_type='".$val."'
                        AND tqp.del_flag = 0
                        GROUP BY
                            q.id
                        ORDER BY
                            tqp.sequence"; //AND q.status='questionStatus.approved'
                $result = \Yii::$app->db->createCommand($sql)->queryAll();
                $result_answer = array_merge($result_answer,$result);
            }
            if($result_answer)
            {
                $result_sql = "SELECT ques_id FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                $params = [':resultId' => $resultId];
                $ques_id = Yii::$app->db->createCommand($result_sql)
                    ->bindValues($params)
                    ->queryColumn();
                foreach ($result_answer as $key => $value)
                {
                    if(in_array($value['id'], $ques_id))
                    {
                        $sql1 = "SELECT is_correct,points_awarded FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                        $is_correct = Yii::$app->db->createCommand($sql1)->queryOne();
                        $result_answer[$key]['is_correct'] = $is_correct['is_correct'];
                        $result_answer[$key]['score'] = !empty($is_correct['points_awarded'])?$is_correct['points_awarded']:'0.00';
                    }
                    else
                    {
                        $result_answer[$key]['score'] = "0.00";
                    }
                }
                $data['evaluated_time'] = $record['end_time'];
                $data['answer'] = ArrayHelper::array_is_null($result_answer);
                $data['score'] = !empty($record['score'])?$record['score']:'0.00';
                $quiz_name = TQuizInfo::findOne($quizId);
                if($quiz_name)
                {
                    $data['quiz_name'] = $quiz_name->quiz_name;
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $data,
                    'success' => true,
                    'code' => '200'
                ];
                Yii::$app->end(json_encode($result));
            }
            else
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
    }
    /**
     * APP学生查看解析（全部解析和错题解析）接口
     * @param int  resultId:答题卡ID quizId:测验 flag:flag token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-24
     * @author: gaoyj
     */
    public function actionAppSeeAllAnalyze()
    {
        $error = array();
        $resultId = isset($_REQUEST['resultId'])?$_REQUEST['resultId']:$error[]=array('答题卡ID不能为空');
        $quizId = isset($_REQUEST['quizId'])?$_REQUEST['quizId']:$error[]=array('测验ID不能为空');
        $flag = isset($_REQUEST['flag'])?$_REQUEST['flag']:$error[]=array('类型不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('token不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if (empty($device)) {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $sql1 = "SELECT
                        id
                    FROM
                        t_quiz_result q
                    WHERE
                        q.status = 'quizResultStatus.marked'
                    AND quiz_id = '".$quizId."'
                    AND del_flag=0
                    GROUP BY
                        create_by";
            $res_id = \Yii::$app->db->createCommand($sql1)
                                ->queryColumn();
            $resId = implode("','", $res_id);
            if ($flag=='all') {
                $paperId = TQuizPaperRelation::find()->where('quiz_id=:quizId',[':quizId' => $quizId])->one()->paper_id;
                $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
                $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
                $result_answer = array();
                foreach ($Type as $key => $val) {
                    $sql = "SELECT
                                q.id,q.content,q.answ_note,q.type,'' as selected,".count($res_id)." AS res_num
                            FROM
                                t_quiz_paper_ques_relation tqp
                            LEFT JOIN t_quiz_question q ON q.id = tqp.ques_id
                            WHERE
                                tqp.paper_id = '".$paperId."' 
                            AND tqp.ques_type='".$val."'
                            AND tqp.del_flag = 0
                            GROUP BY
                                q.id
                            ORDER BY
                                tqp.sequence"; //AND q.status='questionStatus.approved'
                    $result = \Yii::$app->db->createCommand($sql)->queryAll();
                    $result_answer = array_merge($result_answer,$result);
                }
                if ($result_answer) {
                    $result_sql = "SELECT ques_id FROM t_quiz_result_answer WHERE result_id=:resultId AND del_flag=0";
                    $params = [':resultId' => $resultId];
                    $ques_id = Yii::$app->db->createCommand($result_sql)
                        ->bindValues($params)
                        ->queryColumn();
                    foreach ($result_answer as $key =>& $value) {
                        if (in_array($value['id'], $ques_id)) {
                            $sql1 = "SELECT answer FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                            $answer = Yii::$app->db->createCommand($sql1)->queryOne();
                            $value['selected'] = $answer['answer'];
                        }
                        $file_sql = "SELECT CASE
                                                WHEN image_uri = '' THEN
                                                    ''
                                                ELSE
                                                    CONCAT(
                                                        '".Yii::$app->params['fileUrl']."',
                                                        image_uri
                                                    )
                                                END AS image_uri,id,name FROM t_quiz_result_answer_file WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                        $file = Yii::$app->db->createCommand($file_sql)->queryAll();
                        $value['file'] = $file;
                    }
                }
            }
            if ($flag=='error') {
                $paperId = TQuizPaperRelation::find()->where('quiz_id=:quizId',[':quizId' => $quizId])->one()->paper_id;
                $type_sql = "select type from t_paper_type_relation where paper_id='".$paperId."' and del_flag=0 order by px ";
                $Type = Yii::$app->db->createCommand($type_sql)->queryColumn();
                $result_answer = array();
                //获取全部试题
                foreach ($Type as $key => $val) {
                    $sql = "SELECT
                                q.id,q.content,q.answ_note,q.type,'' as selected,".count($res_id)." AS res_num,tqp.score
                            FROM
                                t_quiz_paper_ques_relation tqp
                            LEFT JOIN t_quiz_question q ON q.id = tqp.ques_id
                            WHERE
                                tqp.paper_id = '".$paperId."'   
                            AND tqp.ques_type='".$val."'
                            AND tqp.del_flag = 0
                            GROUP BY
                                q.id
                            ORDER BY
                                tqp.sequence";//AND q.status='questionStatus.approved'
                    $result = \Yii::$app->db->createCommand($sql)->queryAll();
                    $result_answer = array_merge($result_answer,$result);
                }
                $sql = "SELECT
                            ques_id
                        FROM
                            t_quiz_result_answer
                        WHERE
                            result_id =:resultId
                        -- AND is_correct=:is_correct 
                        AND del_flag = 0";
                $params = [':resultId' => $resultId];
                $quesIds = \Yii::$app->db->createCommand($sql)
                                    ->bindValues($params)
                                    ->queryColumn();
                foreach ($result_answer as $key => $value) {
                    if (in_array($value['id'], $quesIds)) {
                        $sql1 = "SELECT answer,points_awarded FROM t_quiz_result_answer WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                        $answer = Yii::$app->db->createCommand($sql1)->queryOne();
                        if ($answer['points_awarded']==$value['score']) {
                            unset($result_answer[$key]);
                            continue;
                        } else {
                            $result_answer[$key]['selected'] = $answer['answer'];
                        }              
                    } else {
                        $select_sql = "SELECT
                                            answer
                                        FROM
                                            t_quiz_result_answer
                                        WHERE
                                            result_id =:resultId
                                        AND ques_id =:id
                                        AND del_flag = 0";
                        $answerParams = [':resultId' => $resultId,':id' => $value['id']];
                        $answer = \Yii::$app->db->createCommand($select_sql)->bindValues($answerParams)->queryOne();
                        if ($answer) {
                            $result_answer[$key]['selected'] = $answer['answer'];
                        }
                    }
                    $file_sql = "SELECT CASE
                                                WHEN image_uri = '' THEN
                                                    ''
                                                ELSE
                                                    CONCAT(
                                                        '".Yii::$app->params['fileUrl']."',
                                                        image_uri
                                                    )
                                                END AS image_uri,id,name FROM t_quiz_result_answer_file WHERE ques_id='".$value['id']."' AND del_flag=0 AND result_id='".$resultId."'";
                    $file = Yii::$app->db->createCommand($file_sql)->queryAll();
                    $result_answer[$key]['file'] = $file;
                }
            }
            if ($result_answer) {
                $result_answer = ArrayHelper::array_is_null($result_answer);
                $allData = array();
                foreach ($result_answer as $in){
                    if ($in['res_num']==0) {
                        $in['percentage'] = 0;
                    } else {
                        // $sql2 = "SELECT COUNT(*) as num FROM t_quiz_result_answer WHERE result_id IN('".$resId."') AND ques_id='".$in['id']."' AND is_correct='yesOrNo.yes'";
                        $sql2 = "SELECT COUNT(*) as num FROM t_quiz_result_answer a LEFT JOIN t_quiz_result q ON q.id=a.result_id WHERE q.status = 'quizResultStatus.marked' AND q.quiz_id = '".$quizId."' AND q.del_flag=0 AND a.ques_id='".$in['id']."' AND a.is_correct='yesOrNo.yes'";
                        $res = \Yii::$app->db->createCommand($sql2)
                                    ->queryScalar();
                        $in['percentage'] = round($res/count($res_id)*100);
                    }
                    if (!empty($in['selected'])) {
                        $answer_array = explode(',', $in['selected']);
                        asort($answer_array);
                        $str_answer = implode(',', $answer_array);
                        $in['selected'] = $str_answer;
                    }
                    $sql="select id,answ_code,answ_content,is_right from t_quiz_question_answer where del_flag = 0 and ques_id='".$in['id']."' ORDER BY answ_code";
                    $answers = Yii::$app->db->createCommand($sql)->queryAll();
                    // foreach ($answers as $key => $val) {
                    //     $answers[$key]['answ_content'] = $val['answ_content'];
                    // }
                    $allData[] = array_merge($in,array('answers'=>ArrayHelper::array_is_null($answers)));
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $allData,
                    'success' => true,
                    'code' => '200'
                ];
            } elseif(empty($result_answer)) {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            } elseif($result_answer===false) {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP新增，修改课程笔记接口
     * @param int  title:标题 content:内容 userId:用户ID course_id:课程ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-16
     * @author: gaoyj
     */
    public function actionAppSaveCourseNote()
    {
        $error = array();
        $title = isset($_REQUEST['title'])?$_REQUEST['title']:$error[]=array('标题不能为空');
        $content = !empty($_REQUEST['content'])?$_REQUEST['content']:'';
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>(object)[],
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [
                        'note_id' => '',
                        'old_id' => '',
                    ],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(!empty($_REQUEST['note_id']))
            {
                $transaction = \Yii::$app->db->beginTransaction();
                $flag = false;
                $noteId = $_REQUEST['note_id'];
                $res = \Yii::$app->db->createCommand()->update('t_course_note', [
                                'title' => $title,
                                'content' => $content, 
                                'update_by' => $userId, 
                                'update_time' => date("Y-m-d H:i:s",time())], 
                                'id=:id', [':id'=>$noteId])
                        ->execute();
                $n_old_id = \app\models\TCourseNote::findOne($noteId);
                if($res)
                {
                    $sql = "update t_course_note_file set del_flag = 1  where note_id='".$noteId."'";
                    $file_res = \Yii::$app->db->createCommand($sql)->execute();
                    $file_id = $_REQUEST['file_id'];
                    if(!empty($file_id))
                    {
                        $ids = explode(',', $file_id);
                        $fileId = implode("','",$ids);
                        $sql1 = "update t_course_note_file set del_flag = 0,note_id='".$noteId."'  where id IN('".$fileId."')";
                        $res1 = \Yii::$app->db->createCommand($sql1)->execute();
                        if($res1)
                        {
                            $flag = true;
                        }
                    }
                    else
                    {
                        $flag = true;
                    }
                    if($flag)
                    {
                        $transaction->commit();
                        $result = array(
                                    "msg" => "操作成功",
                                    "ver" => "1.5.0",
                                    'data' => ['old_id'=>$n_old_id->old_id],
                                    'success' => true,
                                    'code' => '200'
                                );
                    }
                    else
                    {
                        $transaction->rollback();
                        $result = array(
                                    "msg" => "操作失败",
                                    "ver" => "1.5.0",
                                    'data' => ['old_id'=>''],
                                    'success' => false,
                                    'code' => '400'
                                );
                    }
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                }
            }
            else
            {
                $db = Yii::$app->db;
                $transaction = $db->beginTransaction();
                $TCourseNote = new \app\models\TCourseNote();
                $uuid = Uuid::uuid();
                $TCourseNote->id = $uuid;
                $TCourseNote->title = $title;
                $TCourseNote->content = $content;
                $TCourseNote->create_by = $userId;
                $TCourseNote->is_share = 'yesOrNo.no';
                $TCourseNote->create_time = date("Y-m-d H:i:s",time());
                $TCourseNote->course_id = $courseId;
                $TCourseNote->old_id = $uuid;
                if($TCourseNote->validate() && $TCourseNote->save())
                {
                    $id = $TCourseNote->attributes['id'];
                    $file_up_flag = false;
                    if(!empty($_REQUEST['file_id']))
                    {
                        $file_id = $_REQUEST['file_id'];
                        $ids = explode(',', $file_id);
                        $fileId = implode("','",$ids);
                        $sql = "update t_course_note_file set note_id = '".$id."'  where id in ('".$fileId."')";
                        $file_res = $db->createCommand($sql)->execute();
                        if($file_res){
                            $file_up_flag = true;
                        }
                    }
                    else
                    {
                        $file_up_flag = true;
                    }
                    if($file_up_flag)
                    {
                        $transaction->commit();
                        $result = array(
                            "msg" => "操作成功",
                            "ver" => "1.5.0",
                            'data' => [
                                'note_id' => $id,
                                'old_id' => $TCourseNote->old_id,
                            ],
                            'success' => true,
                            'code' => '200'
                        );
                        Yii::$app->end(json_encode($result));
                    }
                    else
                    {
                        $transaction->rollback();
                        $result = array(
                            "msg"=> "操作失败",
                            "ver"=> "1.5.0",
                            'data' => [
                                'note_id' => '',
                                'old_id' => '',
                            ],
                            'success' => false,
                            'code'=>'400'
                        );
                    }
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                }
                else
                {
                    $result = array(
                        "msg"=> "操作失败",
                        "ver"=> "1.5.0",
                        'data' => [
                            'note_id' => '',
                            'old_id' => '',
                        ],
                        'success' => false,
                        'code'=>'400'
                    );
                    Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
                }
            }
        }
    }
    /**
     * APP课程笔记列表接口
     * @param int  title:标题 content:内容 userId:用户ID course_id:课程ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-16
     * @author: gaoyj
     */
    public function actionAppGetCourseNoteList()
    {
        $error = array();
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:'';
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $pageSize = isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:'20';
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:'1';
        $limit = "limit ".($page-1)*$pageSize.",$pageSize";
        $output = array();        
        if(!empty($error))
        {
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            if(empty($courseId))
            {
                $where = " tcn.create_by =:userId ";
            }
            else
            {
                $where = " (tcn.is_share = 'yesOrNo.yes' OR tcn.create_by =:userId) AND tcn.course_id='".$courseId."' ";
            }
            // $sql_conut = "select count(id) sum from t_course_note tcn where ".$where." create_by='".$userId."' and del_flag=0";
            // $count = Yii::$app->db->createCommand($sql_conut)->queryOne();            
            $sql = "SELECT
                        tcn.*,tci.name AS course_name,'' as is_myNote
                    FROM
                        t_course_note tcn
                    LEFT JOIN t_course_info tci ON tci.id = tcn.course_id
                    WHERE
                    ".$where."
                    AND tcn.del_flag = 0
                    ORDER BY
                        tcn.create_time DESC,
                        tcn.update_time DESC ".$limit."";
            $note_res = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId])->queryAll();
            if($note_res)
            {
                $note_res = ArrayHelper::array_is_null($note_res);
                foreach ($note_res as $record)
                {
                    $record['content'] = str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($record['content'])));
                    $record['note_files']['image'] = array();
                    $record['note_files']['video'] = array();
                    $record['note_files']['audio'] = array();
                    $record['note_files']['material'] = array();
                    // 获取笔记附件
                    $noteid = $record['id'];
                    if($record['create_by']==$userId){
                        $record['is_myNote'] = 'yesOrNo.yes';
                    }else{
                        $record['is_myNote'] = 'yesOrNo.no';
                    }
                    $sql1 = "select * from t_course_note_file where note_id='".$noteid."' and status=0 and del_flag=0";
                    $note_files = Yii::$app->db->createCommand($sql1)->queryAll();
                    foreach ($note_files as $value)
                    {
                        switch ($value['mime'])
                        {
                            case 'application/msword':
                            case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                                $type='word';
                                break;
                            case 'application/vnd.ms-excel':
                            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                                $type='excel';
                                break;
                            case 'application/vnd.ms-powerpoint':
                            case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                                $type='ppt';
                                break;
                            case 'application/pdf':
                                $type='pdf';
                                break;
                            case 'text/plain':
                                $type='txt';
                                break;
                        }
                        $file_info=array();
                        if($value['mime'] == 'image/jpeg'||$value['mime'] == 'image/png'||$value['mime'] == 'image/*' )
                        {
                            $file_info=array(
                                'filename'=>$value['name'],
                                'compress_uri'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',//压缩路径
                                'original_uri'=>!empty($value['image_uri']) ? Yii::$app->params['fileUrl'].$value['image_uri'] : '',//原图路径
                                'thumb_uri'=>!empty($value['thumb_uri']) ? Yii::$app->params['fileUrl'].$value['thumb_uri'] : '',//缩略图路径
                                'original'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',
                                'fid'=>$value['id']
                            );
                            $record['note_files']['image'][] = $file_info;
                        }
                        elseif($value['mime'] == 'video/mp4' && empty($record['note_files']['video']))
                        {
                            // 只显示至多一个视频
                            $record['note_files']['video'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        }
                        elseif($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3')
                        {   
                            // 音频3个
                            $record['note_files']['audio'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        }elseif($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation'|| $value['mime'] == 'application/vnd.ms-powerpoint'|| $value['mime'] == 'text/plain'|| $value['mime'] == 'application/pdf')
                        {
                            $html_url = BaseController::getFileHtmlUrl( Yii::$app->params['fileUrl'].$value['file_uri']);
                            $record['note_files']['material'][] = array(
                                'type'=>$type,
                                'filename'=>$value['name'],
                                'compress_uri'=>$html_url,
                                'original_uri'=>$html_url,
                                'original'=>$html_url,
                                'thumb_uri'=>$html_url,
                                'fid'=>$value['id']
                            );
                        }
                    }
                    $output[] = $record;
                }
                $result = array(
                    "msg"=> "查询成功",
                    "ver"=> "1.5.0",
                    'data'=> $output,
                    'success' => true,
                    'code'=>'200'
                );
            }
            elseif(empty($note_res))
            {
                $result = array(
                    "msg"=> "数据为空",
                    "ver"=> "1.5.0",
                    'data'=>[
                    ],
                    'success' => false,
                    'code'=>'404'
                );
            }
            elseif($note_res===false)
            {
                $result = array(
                    "msg"=> "查询失败",
                    "ver"=> "1.5.0",
                    'data'=>[
                    ],
                    'success' => false,
                    'code'=>'400'
                );
            }
            Yii::$app->end(json_encode($result));            
        }
    }
    /**
     * APP课程笔记详情接口
     * @param int  note_id:笔记ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-17
     * @author: gaoyj
     */
    public function actionAppGetNoteContent()
    {
        $error = array();
        $noteId = isset($_REQUEST['noteId'])?$_REQUEST['noteId']:$error[]=array('笔记ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
            }
            $sql = "select * from t_course_note where id=:id and del_flag=0";
            $params = [':id' => $noteId];
            $note_res = \Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryOne();
            if($note_res)
            {
                $note_res = ArrayHelper::array_is_null($note_res);
                $note_res['content'] = $note_res['content'];
                $note_res['note_files']['image'] = array();
                $note_res['note_files']['video'] = array();
                $note_res['note_files']['audio'] = array();
                $note_res['note_files']['material'] = array();
                // 获取笔记附件
                $sql1 = "select * from t_course_note_file where note_id='".$noteId."' and status=0 and del_flag=0";
                $note_files = Yii::$app->db->createCommand($sql1)->queryAll();
                if($note_files)
                {
                    foreach ($note_files as $value) {
                        switch ($value['mime']) {
                            case 'application/msword':
                            case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                                $type='word';
                                break;
                            case 'application/vnd.ms-excel':
                            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
                                $type='excel';
                                break;
                            case 'application/vnd.ms-powerpoint':
                            case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                                $type='ppt';
                                break;
                            case 'application/pdf':
                                $type='pdf';
                                break;
                            case 'text/plain':
                                $type='txt';
                                break;
                        }
                        $file_info=array();
                        if ($value['mime'] == 'image/jpeg'|| $value['mime'] == 'image/jpg' ||$value['mime'] == 'image/png'||$value['mime'] == 'image/*' )
                        {
                            $file_info=array(
                                'filename'=>$value['name'],
                                'compress_uri'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',//压缩路径
                                'original_uri'=>!empty($value['image_uri']) ? Yii::$app->params['fileUrl'].$value['image_uri'] : '',//原图路径
                                'thumb_uri'=>!empty($value['thumb_uri']) ? Yii::$app->params['fileUrl'].$value['thumb_uri'] : '',//缩略图路径
                                'original'=>!empty($value['file_uri']) ? Yii::$app->params['fileUrl'].$value['file_uri'] : '',
                                'fid'=>$value['id']
                            );
                            $note_res['note_files']['image'][] = $file_info;
                        } 
                        elseif ($value['mime'] == 'video/mp4' && empty($note_res['note_files']['video']))
                        { 
                            // 只显示至多一个视频
                            $note_res['note_files']['video'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//压缩路径
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//原图路径
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//缩略图路径
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'audio/mpeg' || $value['mime'] == 'audio/mp3')
                        { 
                            // 音频3个
                            $note_res['note_files']['audio'][] = array(
                                'filename'=>$value['name'],
                                'compress_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//压缩路径
                                'original_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//原图路径
                                'thumb_uri'=>Yii::$app->params['fileUrl'].$value['file_uri'],//缩略图路径
                                'original'=>Yii::$app->params['fileUrl'].$value['file_uri'],
                                'fid'=>$value['id']
                            );
                        } 
                        elseif ($value['mime'] == 'application/msword' || $value['mime'] == 'application/vnd.ms-excel'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'|| $value['mime'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation'|| $value['mime'] == 'application/vnd.ms-powerpoint'|| $value['mime'] == 'text/plain'|| $value['mime'] == 'application/pdf')
                        {
                            $html_url = BaseController::getFileHtmlUrl( Yii::$app->params['fileUrl'].$value['file_uri']);
                            $note_res['note_files']['material'][] = array(
                                'type'=>$type,
                                'filename'=>$value['name'],
                                'original_uri'=>$html_url,
                                'original'=>$html_url,
                                'compress_uri'=>$html_url,
                                'thumb_uri'=>$html_url,
                                'fid'=>$value['id']
                            );
                        }
                    }
                }
                $result = array(
                    "msg" => "查询成功",
                    "ver" => "1.5.0",
                    'data' => $note_res,
                    'success' => true,
                    'code' => '200'
                );
            }
            elseif(empty($note_res))
            {
                $result = array(
                    "msg" => "数据为空",
                    "ver" => "1.5.0",
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                );
            }
            elseif($note_res===false)
            {
                $result = array(
                    "msg" => "查询失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP删除笔记接口
     * @param int  note_id:笔记ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-18
     * @author: gaoyj
     */
    public function actionAppDeleteCourseNote()
    {
        $error = array();
        $noteId = isset($_REQUEST['noteId'])?$_REQUEST['noteId']:$error[]=array('笔记ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $flag = false;
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $transaction = Yii::$app->db->beginTransaction();
            $res = \Yii::$app->db->createCommand()->update('t_course_note', [
                                'del_flag' => 1], 
                                'id=:id', [':id'=>$noteId])
                        ->execute();
            if($res)
            {
                $file = \app\models\TCourseNoteFile::find()->where('note_id=:noteId', [':noteId' => $noteId])->one();
                if(!empty($file))
                {
                    $res1 = \app\models\TCourseNoteFile::updateAll(['del_flag'=>1],['note_id'=>$noteId]);
                    if($res1)
                    {
                        $flag = true;
                    }
                    else
                    {
                        $flag = false;
                    }
                }
                else
                {
                    $flag = true;
                }
                if($flag)
                {
                    $transaction->commit();
                    $result = [
                        'msg' => '删除成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $transaction->rollback();
                    $result = [
                        'msg' => '删除失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $result = [
                    'msg' => '删除失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP分享笔记接口
     * @param int  note_id:笔记ID userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-07-18
     * @author: gaoyj
     */
    public function actionAppShareCourseNote()
    {
        $error = array();
        $noteId = !empty($_REQUEST['noteId'])?$_REQUEST['noteId']:$error[]=array('笔记ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $token = !empty($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $status = !empty($_REQUEST['status'])?$_REQUEST['status']:$error[]=array('状态不能为空');
        $projectId = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $res = \Yii::$app->db->createCommand()->update('t_course_note',[
                            'is_share' => $status,
                            'update_by' => $userId,
                            'update_time' => date("Y-m-d H:i:s")],
                            'id=:id', [':id' => $noteId])
                        ->execute();
            if($res)
            {
                $result = [
                    'msg' => '分享成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '分享失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP修改视频进度接口
     * @param int  note_id:笔记ID userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-03
     * @author: gaoyj
     */
    public function actionAppSaveMyVideoRate()
    {
        $error = array();
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $itemId = !empty($_REQUEST['itemId'])?$_REQUEST['itemId']:$error[]=array('章节ID不能为空');
        $fileId = !empty($_REQUEST['fileId'])?$_REQUEST['fileId']:$error[]=array('视频ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $type = !empty($_REQUEST['type'])?$_REQUEST['type']:$error[]=array('类型不能为空');
        $current_progress = !empty($_REQUEST['current_progress'])?$_REQUEST['current_progress']:$error[]=array('进度不能为空');
        $is_end = !empty($_REQUEST['is_end'])?$_REQUEST['is_end']:'';
        $token = !empty($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $data = \app\models\TCourseItemsVideoCurrent::find()
                    ->where('course_id=:courseId and item_id=:itemId and resource_id=:fileId and user_id=:userId and del_flag=0', [
                            ':courseId' => $courseId,
                            ':itemId' => $itemId,
                            ':fileId' => $fileId,
                            ':userId' => $userId
                        ])
                    ->one();
            if(!empty($data))
            {
                if($data->current_progress>$current_progress){
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => true,
                        'code' => '200'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $data->current_progress = $current_progress;
                if(!empty($is_end))
                {
                    $data->is_end = $is_end;
                }
                $data->update_by = $userId;
                $data->update_time = date("Y-m-d H:i:s");
                if($data->save())
                {
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '操作失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $model = new \app\models\TCourseItemsVideoCurrent();
                $model->attributes = $_REQUEST;
                $model->id = Uuid::uuid();
                $model->course_id = $courseId;
                $model->item_id = $itemId;
                $model->resource_id = $fileId;
                $model->type = $type;
                $model->user_id = $userId;
                $model->current_progress = $current_progress;
                $model->is_end = $is_end;
                $model->create_by = $userId;
                $model->create_time = date("Y-m-d H:i:s");
                $model->del_flag = 0;
                if($model->validate() && $model->save())
                {
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '操作失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP获取视频进度接口
     * @param int  note_id:笔记ID userId:用户ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-08-03
     * @author: gaoyj
     */
    public function actionAppGetVideoRate()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $itemId = isset($_REQUEST['itemId'])?$_REQUEST['itemId']:$error[]=array('章节ID不能为空');
        $fileId = isset($_REQUEST['fileId'])?$_REQUEST['fileId']:$error[]=array('视频ID不能为空');
        $type = isset($_REQUEST['type'])?$_REQUEST['type']:$error[]=array('类型不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $token = isset($_REQUEST['token'])?$_REQUEST['token']:$error[]=array('Token不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error)){
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if(empty($device))
            {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => (object)array(),
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $data = \app\models\TCourseItemsVideoCurrent::find()
                    ->where('course_id=:courseId and item_id=:itemId and resource_id=:fileId and user_id=:userId and del_flag=0', [
                            ':courseId' => $courseId,
                            ':itemId' => $itemId,
                            ':fileId' => $fileId,
                            ':userId' => $userId
                        ])
                    ->asArray()
                    ->one();
            if($data)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'progress' => $data['current_progress'],
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($data))
            {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [
                        'progress' => '0',
                    ],
                    'success' => false,
                    'code' => '404'
                ];
            }
            elseif($data===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [
                        'progress' => '0',
                    ],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP获取推送消息列表接口
     * @param int  userId:用户ID token:token
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-10-31
     * @author: gaoyj
     */
    public function actionAppGetPushMessageList()
    {
        $error      = array();
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]=array('用户ID不能为空');
        $token      = isset($_REQUEST['token']) && !empty($_REQUEST['token']) ? $_REQUEST['token'] : $error[]=array('Token不能为空');
        $pageSize   = isset($_REQUEST['pageSize']) && !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $page       = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page']:'1';
        $offset     = ($page-1)*$pageSize;
        $limit      = "limit ".$offset.",$pageSize";
        if (!empty($error)) {
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if (empty($device)) {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => array(),
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $sql = "SELECT b.id,b.course_id,'' as push_content,'' as title,IFNULL(b.update_time,b.create_time) as create_time,b.type,'' as t_old_id,'' as b_old_id "
                    . "FROM t_course_member a "
                    . "LEFT JOIN t_course_signin_info b ON a.course_id = b.course_id "
                    . "LEFT JOIN t_course_signin_student c ON b.id = c.sign_id "
                    . "WHERE a.user_id =:userId AND a.del_flag = 0 AND b.del_flag = 0 AND b.type='signinType.common' AND c.del_flag = 0 AND c.student_status = 'signinStatus.default' AND c.user_id =:userId "
                    . "UNION ALL "
                    . "SELECT tcp.id,tcp.course_id,tcp.push_content,tcp.title,tcp.create_time,'pushType.push' AS type,'' as t_old_id,'' as b_old_id " 
                    . "FROM t_course_push tcp "
                    . "LEFT JOIN t_course_push_relation tcpr ON tcp.id = tcpr.push_id " 
                    . "WHERE tcpr.user_id =:userId AND tcpr.del_flag = 0 AND tcp.del_flag = 0 "
                    . "ORDER BY `create_time` DESC $limit";
            $data = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId])->queryAll();
            if (!empty($data)) {
                foreach ($data as $key => $value) {
                    $sql = "SELECT name,old_id FROM t_course_info WHERE id=:id AND del_flag=0";
                    $params = [':id' => $value['course_id']];
                    $course_name = Yii::$app->db->createCommand($sql)
                                ->bindValues($params)
                                ->queryOne();
                    if ($course_name) {
                        $data[$key]['course_name'] = $course_name['name'];
                        $data[$key]['t_old_id'] = $course_name['old_id'];
                    } else {
                        $data[$key]['course_name'] = '';
                    }
                    $data[$key]['b_old_id'] = PdUtils::getOldIdByTid($value['course_id']);
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => ArrayHelper::array_is_null($data),
                    'success' => true,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '数据为空',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP获取证书信息接口
     * @param int  userId:用户ID courseId：课程ID token:token
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-04-10
     * @author: gaoyj
     */
    public function actionAppGetCredit(){
        $error      = array();
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]=array('用户ID不能为空');
        $courseId   = isset($_REQUEST['courseId']) && !empty($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[]=array('课程ID不能为空');
        $token      = isset($_REQUEST['token']) && !empty($_REQUEST['token']) ? $_REQUEST['token'] : $error[]=array('Token不能为空');
        if (!empty($error)) {
            $result = array(
                "msg"=> "参数缺失",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $device = TBaseDevice::find()->where('verify_token=:token and status=:status', [':token' => $token, ':status' => 'effective'])->one();
            if (empty($device)) {
                $result = [
                    'msg' => 'Token失效',
                    'ver' => '1.5.0',
                    'data' => (object)[],
                    'code' => '900'
                ];
                Yii::$app->end(json_encode($result));
            }
            $studentCreditInfo = \app\models\TCourseStudentCredit::findOne(['course_id'=>$courseId,'user_id'=>$userId,'del_flag'=>0]);
            if (!empty($studentCreditInfo)) {
                //学生的信息
                $studentInfo = TBaseUserProfile::find()->where('user_id=:userId and del_flag=0',[':userId'=>$userId])->asArray()->one();
                //课程信息和创建者信息
                $TCourseInfo = TCourseInfo::find()->where(['id'=>$courseId,'del_flag'=>0])->asArray()->one();
                if ($TCourseInfo) {
                    $teacherInfo = TBaseUserProfile::find()->where('user_id=:userId and del_flag=0',[':userId'=>$TCourseInfo['create_by']])->asArray()->one();
                }
                $data['course_name'] = $TCourseInfo['name'];
                $data['content'] = $studentInfo['pet_name'].'已完成'.$TCourseInfo['name'].'课程的学习，总学时为'.$TCourseInfo['total_hour'].'，特发此结业证书。';
                $data['teacher_name'] = '开课教师：'.$teacherInfo['pet_name'];
                $data['date'] = $studentCreditInfo->create_time;
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $data,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '没有证书',
                    'ver' => '1.5.0',
                    'data' => (object)[],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP获取论坛开启状态接口
     * @param int  courseId:课程ID token:token
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-10-31
     * @author: gaoyj
     */
    public function actionAppForumStatus(){
        $error      = array();
        $courseId   = isset($_REQUEST['courseId']) && !empty($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[]=array('课程ID不能为空');
        if (!empty($error)) {
            $result = array(
                "msg" => "参数缺失",
                "ver" => "1.5.0",
                'data' => [],
                'code' => '601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            $forum = \app\models\TForum::find()->where(['course_id'=>$courseId,'del_flag'=>0])->one();
            if (!empty($forum)) {
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '老师尚未开通论坛，暂无法使用',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /*
     * 答题附件上传
     */
    public function actionAppQuesFilesInput(){
        $error = array();
        $userId = empty($_REQUEST['userId'])?$error[]=array('用户ID不能为空'):$_REQUEST['userId'];
        $courseId = empty($_REQUEST['courseId'])?$error[]=array('课程ID不能为空'):$_REQUEST['courseId'];
        $quesId = empty($_REQUEST['quesId'])?$error[]=array('习题ID不能为空'):$_REQUEST['quesId'];
        $resultId = empty($_REQUEST['resultId'])?$error[]=array('答题卡ID不能为空'):$_REQUEST['resultId'];
        if (!empty($error)) {
            $result = array(
                "msg"=> "缺少参数",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result, JSON_FORCE_OBJECT));
        } else {
            if (!empty($_FILES)) {
                $projectId = TCourseInfo::findOne($courseId)['project_id'];
                if(!empty($projectId)){
                    $path = 'files'.DIRECTORY_SEPARATOR.$projectId.DIRECTORY_SEPARATOR.'student'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.$userId.DIRECTORY_SEPARATOR.$resultId.DIRECTORY_SEPARATOR.$quesId.DIRECTORY_SEPARATOR;
                } else {
                    $path = 'files'.DIRECTORY_SEPARATOR.'student'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.$userId.DIRECTORY_SEPARATOR.$resultId.DIRECTORY_SEPARATOR.$quesId.DIRECTORY_SEPARATOR;
                }
                if (!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)) {
                    mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
                }
                $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
                $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
                if (move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)) {
                    if ($fileformat == 'mp4') {
                        exec("/usr/local/ffmpeg2/bin/ffmpeg -i " . \Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//", $res, $code);
                        if ($code == 0) {
                            $play_time = $res[0];
                        }
                    }
                    $model = new \app\models\TQuizResultAnswerFile();
                    $model->id=Uuid::uuid();
                    $model->ques_id=$quesId;
                    $model->name=$_FILES['files']["name"];
                    $model->image_uri=$uri;;
                    $model->size= $_FILES['files']["size"];
                    $model->create_by = $userId;
                    $model->create_time = date('Y-m-d H:i:s', time());
                    $model->type = $fileformat;
                    $model->mime = $_FILES['files']["type"];
                    $model->del_flag = 0;
                    if ($model->validate() && $model->save()) {
                        $arr = array(
                                    'fid'=>$model->id,
                                    'filename' => $_FILES['files']["name"],
                                    'type' => $_FILES['files']["type"],
                                    'size' => $_FILES['files']["size"],
                                    'url' => Yii::$app->params['fileUrl'].$uri
                                );
                        $result = array(
                            "msg"=> "保存成功",
                            "ver"=> "1.5.0",
                            'data'=> $arr,
                            'code'=>'200'
                        );
                    }
                    else
                    {
                        $result = array(
                            "msg"=> "保存失败",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'code'=>'400'
                        );
                    }
                }else{
                    $result = array(
                        "msg"=> "上传失败",
                        "ver"=> "1.5.0",
                        'data'=>array(),
                        'success' => false,
                        'code'=>'400'
                    );
                }
            }
            Yii::$app->end(urldecode(json_encode($result, JSON_FORCE_OBJECT)));
        }
    }
    /**
     * APP返回轮播图接口
     * @param int  courseId:课程ID bcourseId:模板课程ID token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2018-09-28
     * @author: gaoyj
     */
    public function actionAppGetFigure()
    {
        $data = array(Yii::$app->params['fileUrl'].'files/app/app_main_images_1.png',Yii::$app->params['fileUrl'].'files/app/app_main_images_2.png',Yii::$app->params['fileUrl'].'files/app/app_main_images_3.png',Yii::$app->params['fileUrl'].'files/app/app_main_images_4.png');
        $result = array(
            'msg' => '查找成功',
            'ver' => '1.5.0',
            'data' => $data,
            'code' => '200'
        );
        Yii::$app->end(urldecode(json_encode($result)));
    }
    function secToTime($times){
        $result = '00:00:00';
        if ($times>0) {
            $hour = floor($times/3600);
            $minute = floor(($times-3600 * $hour)/60);
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            if($hour==0)
            {
                $result = $minute.':'.$second;
            }
            else
            {
                $result = $hour.':'.$minute.':'.$second;
            } 
        }
        return $result;
    }
}